public class Sort {
public static void main(String[] args) {
int[] arr = RandomUtil.randomInts(100);
System.out.println(JSONObject.toJSON(arr));
System.out.println();
quickSort(arr, 0, arr.length - 1);
System.out.println(JSONObject.toJSON(arr));
}
/**
* 快速排序
* @param arr
* @param left
* @param right
*/
public static void quickSort(int[] arr, int left, int right) {
int l = left;
int r = right;
int midValue = arr[(left + right) / 2];
int temp = 0;
//左边比右边小,可以排序
while (l < r) {
while (arr[l] < midValue) {
l++;
}
while (arr[r] > midValue) {
r--;
}
if (l >= r) break;
temp = arr[r];
arr[r] = arr[l];
arr[l] = temp;
if (arr[l] == midValue) {
r++;
}
if (arr[r] == midValue) {
l--;
}
}
//如果左边等于右边,手动移动
if (l == r) {
l++;
r--;
}
if (l < right) {
quickSort(arr, l, right);
}
if (r > left) {
quickSort(arr, left, r);
}
}