快速排序

快速排序_第1张图片

 

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
 */

 为了提高快速排序算法的性能,可以采用随机选择策略进行划分

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 = randomizedPartition(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;
    }
    //随机选择策略
    private static int randomizedPartition(int[] a, int left, int right){
        int pivot = (int)(left + Math.random() * (right - left));
        exchange(a, pivot, left);
        return partition(a, left, right);
    }
}
/*
输出:2 3 5 6 8 10 11 13
 */

 最坏时间复杂度:O(n^2)

平均时间复杂度:O(nlogn)

稳定性:不稳定

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