快速排序-Java实现

看到快排就想到之前的导员了,记得当初期末代码题就是手写快排
逻辑就不写了,看看代码基本都懂了

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {8,1,2,4,5,6,7};

//        int[] arr = {4,6,2,3,1,5,7,8};
        /**
         * 1,6,2,3,1,5,7,8
         * 1,6,2,3,6,5,7,8
         * 1,3,2,3,6,5,7,8
         * 1,3,2,4,6,5,7,8
         */
        quickSort(arr,0,arr.length-1);
        for (int i:arr){
            System.out.print(i + "\t");
        }
    }

    private static void quickSort(int[] arr, int leftIndex, int rightIndex){
        if (leftIndex >= rightIndex){
            return;
        }
        int left = leftIndex;
        int right = rightIndex;

        int key = arr[left];

        while (left < right){
            while (right > left && arr[right] >= key){
                right--;
            }

            arr[left] = arr[right];

            while (left < right && arr[left] <= key){
                left++;
            }

            arr[right] = arr[left];
        }
        arr[left] = key;
        quickSort(arr,leftIndex,left-1);
        quickSort(arr,right+1,rightIndex);
    }
}

posted @ 2021-08-13 23:12  达达i  阅读(39)  评论(0编辑  收藏  举报