# 快速排序
public class QuickSort {
public static void main(String[] args) {
int[] arr1 = {};
int[] arr2 = {1,2,34,5,6,2,3445,3,4};
int[] arr3 = {2222,1};
quickSort(arr1);
quickSort(arr2);
quickSort(arr3);
printArr(arr1);
printArr(arr2);
printArr(arr3);
}
/**
* 快排
* @param arr
*/
public static void quickSort (int[] arr) {
help(arr, 0, arr.length -1 );
}
public static void help (int[] arr, int left, int right) {
int head = left;
int tail = right;
if (tail <= head) {
return;
}
// 标准值
int standard = arr[head];
int standardIndex = head;
head ++;
// 快排
while(head <= tail) {
// 先从右往左
// 大于的话 tail 就一直往左移
while(tail >= head && arr[tail] >= standard) {
tail--;
}
if (tail < head) {
break;
}
// 交换
arr[standardIndex] = arr[tail];
standardIndex = tail;
// 从左往右移
// 小于的话,head 就一直往右移
while (tail >= head && arr[head] < standard) {
head ++;
}
if (tail < head) {
break;
}
// 交换
arr[standardIndex] = arr[head];
standardIndex = head;
}
// 归位
arr[standardIndex] = standard;
// 递归
help(arr, left, standardIndex - 1);
help(arr, standardIndex + 1, right);
}
public static void printArr(int[] arr) {
System.out.println("=================");
for (int i = 0; i < arr.length; i++) {
System.out.println("arr["+ i + "] = " + arr[i]);
}
System.out.println("=================");
System.out.println();
}
}