Given an array of_n_objects with_k_different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.
Notice
You are not suppose to use the library's sort function for this problem.
k <= n
Example
Given colors=[3, 2, 2, 1, 4],k=4, your code should sort colors in-place to[1, 2, 2, 3, 4].
A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory. Can you do it without using extra memory?
/*Method II:
* Each time sort the array into three parts:
* [all min] [all unsorted others] [all max],
* then update min and max and sort the [all unsorted others]
* with the same method.
*/
public void sortColors22(int[] colors, int k){
int left=0;
int right=colors.length-1;
int i=0;
int min=1;
int max=k;
while(min<max){
while(i<=right){
if(colors[i]==min){
swap(colors,i,left);
i++;
left++;
}else if(colors[i]==max){
swap(colors,i,right);
right--;
//注意这里i不变,因为在要再次判断下交换完的这个数有可能是min
}else{
i++;
}
}
//set i to the first element in unsorted others
i=left;
min++;
max--;
}
}
public void swap(int[] colors,int i,int j){
int temp=colors[i];
colors[i]=colors[j];
colors[j]=temp;
}