快速排序

import java.util.Arrays;

/**
 * @author CHENG 2018/11/3
 */

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = new int[] {3, 5, 1, 7, 6, 4, 7, 8, 2, 9, 8};
        System.out.println(Arrays.toString(arr));

        quickSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    private static void quickSort(int[] a) {
        if(a.length <= 1) return;
        quickSort(a, 0, a.length - 1);
    }

    private static void quickSort(int[] a, int low, int high) {
        if(low >= high) return;

        int i = low;
        int j = high;
        int pivot = a[i];

        while (i < j) {
            while (i < j && a[j] > pivot) j--;
            while (i < j && a[i] <= pivot) i++;     //此处如果不加等号,i无法前进
            swap(a, i ,j);
        }
        swap(a, low, i);

        quickSort(a, low, i - 1);
        quickSort(a, i + 1, high);
    }

    private static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

}

你可能感兴趣的:(快速排序)