快速排序,它的基本思想是在一个数组中找到一个基准值,然后从左右两边开始比较交换,每次将一小部分排成有序,经过多次排序来达到整体是有序。用到了分而治之的思想。
public class QuickSort {
private static int count = 0;
public static void main(String[] args) {
// int[] arr = {9,3,2,1,10,6,8,7,5,4};
int[] arr = {1,88,23,4,52,3,7};
System.out.println(Arrays.toString(arr));
quickSort(arr,0,arr.length-1);
}
private static void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int emptyIndex = right;
int i = left, j = right;
int key = arr[emptyIndex];
while (i < j) {
// 从左开始比较,找出大的值,如果i比基准值大,那就要把i放到右边去
while (i < j && arr[i] < key) {
i++;
}
if (i < j) {
arr[emptyIndex] = arr[i];
emptyIndex = i;
}
// 从右开始比较,找出小的值,如果j比基准值小,那就要把i放到左边去
while (i < j && arr[j] > key) {
j--;
}
if (i < j) {
arr[emptyIndex] = arr[j];
emptyIndex = j;
}
}
arr[emptyIndex] = key;
count ++;
System.out.println("count: " + count +", i:"+i+", "+", j:"+j+", "+ Arrays.toString(arr));
quickSort(arr,left,i-1);
quickSort(arr,i+1,right);
}
}