Java快速排序

记录下

 public static void main(String[] args) {
        Demo demo = new Demo();
        int[] arr = {1, 78, 56, 213, 86, 5642, 8, 89, 456, 345, 234, 7};
        demo.quickSort(arr, 0, arr.length - 1);
        //demo.bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int partition = partition(arr, low, high);
            quickSort(arr, low, partition - 1);
            quickSort(arr, partition + 1, high);
        }
    }

    public int partition(int[] arr, int low, int high) {
        int temp = arr[low];
        int pivot = arr[low];

        while (low < high) {
            while (low < high && arr[high] >= pivot) high--;
            arr[low] = arr[high];
            while (low < high && arr[low] <= pivot) low++;
            arr[high] = arr[low];
        }
        arr[low] = temp;
        return low;
    }

    public void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
posted @ 2019-07-20 17:28  这谁顶着住啊  阅读(146)  评论(0编辑  收藏  举报