快速排序,它的基本思想是在一个数组中找到一个基准值,然后从左右两边开始比较交换,每次将一小部分排成有序,经过多次排序来达到整体是有序。用到了分而治之的思想。

    1. public class QuickSort {
    2. private static int count = 0;
    3. public static void main(String[] args) {
    4. // int[] arr = {9,3,2,1,10,6,8,7,5,4};
    5. int[] arr = {1,88,23,4,52,3,7};
    6. System.out.println(Arrays.toString(arr));
    7. quickSort(arr,0,arr.length-1);
    8. }
    9. private static void quickSort(int[] arr, int left, int right) {
    10. if (left >= right) {
    11. return;
    12. }
    13. int emptyIndex = right;
    14. int i = left, j = right;
    15. int key = arr[emptyIndex];
    16. while (i < j) {
    17. // 从左开始比较,找出大的值,如果i比基准值大,那就要把i放到右边去
    18. while (i < j && arr[i] < key) {
    19. i++;
    20. }
    21. if (i < j) {
    22. arr[emptyIndex] = arr[i];
    23. emptyIndex = i;
    24. }
    25. // 从右开始比较,找出小的值,如果j比基准值小,那就要把i放到左边去
    26. while (i < j && arr[j] > key) {
    27. j--;
    28. }
    29. if (i < j) {
    30. arr[emptyIndex] = arr[j];
    31. emptyIndex = j;
    32. }
    33. }
    34. arr[emptyIndex] = key;
    35. count ++;
    36. System.out.println("count: " + count +", i:"+i+", "+", j:"+j+", "+ Arrays.toString(arr));
    37. quickSort(arr,left,i-1);
    38. quickSort(arr,i+1,right);
    39. }
    40. }