Three color sort


Given a linear integer array (which has only 0s, 1s, 2s) in unsorted fashion, you need to sort that array with very minimal swaps and visit to the node. public class Answer implements ThreeColorSortInterface { @Override public void PerformThreeColorSort(ColorArray colArray) { // WRITE YOUR CODE HERE return ; } public static void main(String [] args) { // write code here to test } } Here is the ColorArray.java class (only for reference). public class ColorArray { private int[] mArr; private int mSize; public ColorArray(int [] arr, int size){ this.mArr = arr; this.mSize = size; } public int GetSize(){ return this.mSize; } public int GetColor(int index){ if(index <0 || index >= this.mSize) return -1; return this.mArr[index]; } // return true on successful swap public boolean Swap(int index1, int index2){ if(index1 <0 || index1 >= this.mSize) return false; if(index2 <0 || index2 >= this.mSize) return false; int temp = this.mArr[index1]; this.mArr[index1] = this.mArr[index2]; this.mArr[index2] = temp; return true; } } Example1: Input: {0, 1, 1, 0, 2} Output:{0, 0, 1, 1, 2} Example2: Input: {2,2,1,1,0,0,1,1,2,2} Output:{0,0,1,1,1,1,2,2,2,2}

Answer

No comments:

Post a Comment