一、快排思想
从一组中选出一个数来,将小于这个数的放在左边,大于这个数的放在右边。这个样每次选出一个数来,经过N次以后每个数就是有序的
二、编码思想及代码
编码思想
1、[i]==num,i++;//num为我们选出来的这个数
2、[i]<num,则[i]于小于区域的临界点的右边一个数交换,小于区++,i++;
3、[i]>num,则[i]与大于区临界点的左边一个数交换,大于区–,i不变;
代码
public static void process3(int[] arr, int L, int R) {
if (L >= R) {
return;
}
swap(arr, L + (int) (Math.random() * (R - L + 1)), R);
int[] equalArea = netherlandsFlag(arr, L, R);
process3(arr, L, equalArea[0] - 1);
process3(arr, equalArea[1] + 1, R);
}
public static int[] netherlandsFlag(int[] arr, int L, int R) {
if (L > R) {
return new int[] { -1, -1 };
}
if (L == R) {
return new int[] { L, R };
}
int less = L - 1; // < 区 右边界
int more = R; // > 区 左边界
int index = L;
while (index < more) {
if (arr[index] == arr[R]) {
index++;
} else if (arr[index] < arr[R]) {
swap(arr, index++, ++less);
} else { // >
swap(arr, index, --more);
}
}
swap(arr, more, R);
return new int[] { less + 1, more };
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}