快速排序

扫码查看
public class Main{
    public static void main(String[] args){
        int[] a  = {6, 10, 13, 5, 8, 3, 2, 11};
        quickSort(a, 0, a.length - 1);
        for(int num : a){
            System.out.print(num + " ");
        }
    }
    public static void quickSort(int[] a, int left, int right){
        if(left < right){
            int pivot = partition(a, left, right);
            quickSort(a, left, pivot - 1);
            quickSort(a, pivot + 1, right);
        }
    }
    public static int partition(int[] a, int left, int right){
        int pivot = a[left];
        int smallIndex = left;
        for(int largeIndex = left + 1; largeIndex <= right; largeIndex ++){
            if(a[largeIndex] < pivot){
                smallIndex ++;
                exchange(a, smallIndex, largeIndex);
            }
        }
        exchange(a, left, smallIndex);
        return smallIndex;
    }
    public static void exchange(int[] a, int index1, int index2){
        int temp = a[index1];
        a[index1] = a[index2];
        a[index2] = temp;
    }
}
/*
output: 2 3 5 6 8 10 11 13
 */
02-01 14:52
查看更多