用快速排序法将数组{2,1,7,9,7,6,4,2,3,5}按升序排列

public class Kuaisu {

    public static void main(String[] args) {
        int[] arr = {2,1,7,9,7,6,4,2,3,5};
        quickSort(arr, 0, arr.length - 1);
        printArr(arr);
    }
    
    private static int partition(int[] arr, int left, int right){
        int temp = arr[left];
        while (right > left){
            // 先判断基准数和后面的数依次比较
            while (temp <= arr[right] && left < right) {
                --right;
            }
            // 当基准数大于了 arr[right],则填坑
            if (left < right) {
                arr[left] = arr[right];
                ++left;
            }
            // 现在是 arr[right] 需要填坑了
            while (temp >= arr[left] && left < right) {
                ++left;
            }
            if (left < right) {
                arr[right] = arr[left];
                --right;
            }
        }
        arr[left] = temp;
        return left;
    }

    public static void quickSort(int[] arr, int left, int right) {
        if (arr == null || left >= right || arr.length <= 1)
            return;
        int mid = partition(arr, left, right);
        quickSort(arr, left, mid);
        quickSort(arr, mid + 1, right);
    }
    //打印
    public static void printArr(int[] arr) {
        for (int anArr : arr) {
            System.out.print(anArr + " ");
        }
    }


}

你可能感兴趣的:(Java)