http://www.lintcode.com/en/problem/sort-colors-ii/
一共k種顏色,進行排序
快排思想,找到fromColor到toColor的中點mid,將colors分爲小於等於mid的和大於mid的兩個部分,然後遞歸排序
class Solution {
public void sortColors2(int[] colors, int k) {
// write your code here
qSort(colors, 0, colors.length - 1, 1, k);
}
private void qSort(int[] colors, int left, int right, int fromCol, int toCol) {
if (left >= right) {
return;
}
if (fromCol >= toCol) {
return;
}
int mid = fromCol + (toCol - fromCol) / 2;
int beg = left;
int end = right;
while (beg <= end) {
while (beg <= end && colors[beg] <= mid) {
beg++;
}
while (beg <= end && colors[end] > mid) {
end--;
}
if (beg <= end) {
int temp = colors[beg];
colors[beg] = colors[end];
colors[end] = temp;
beg++;
end--;
}
}
qSort(colors, left, end, fromCol, mid);
qSort(colors, beg, right, mid + 1, toCol);
}
}