其他分享
首页 > 其他分享> > 快速排序法03:双路快速排序法

快速排序法03:双路快速排序法

作者:互联网

为了解决数组中重复元素过多导致的性能退化,重新思考partition()方法的逻辑,在原有的基础上,从两端分别进行比较大小

循环不变量:arr[left + 1, i - 1] <= v,arr[j + 1, right] >= v

import java.util.Arrays;
import java.util.Random;

public class Algorithm {

    public static void main(String[] args) {

        Integer[] arr = {3, 2, 5, 1, 0, 0};
        QuickSort.sort2ways(arr);

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

class QuickSort {

    private QuickSort(){}

    public static<E extends Comparable<E>> void sort2ways(E[] arr){

        Random random = new Random();
        E temp = null;
        sort2ways(arr, 0, arr.length - 1, temp, random);
    }

    public static<E extends Comparable<E>> void sort2ways(E[] arr, int left, int right, E temp, Random random){

        if (left >= right){
            return;
        }

        int p = partition2ways(arr, left, right, temp, random);

        sort2ways(arr, left, p - 1, temp, random);
        sort2ways(arr, p + 1, right, temp, random);
    }

    /**
     * 循环不变量:arr[left + 1, i - 1] <= v,arr[j + 1, right] >= v
     */
    public static <E extends Comparable<E>> int partition2ways(E[] arr, int left, int right, E temp, Random random){

        /**
         * 随机选择标定点,和第一个元素互换
         */
        int p = random.nextInt(right - left + 1) + left;

        temp = arr[p];
        arr[p] = arr[left];
        arr[left] = temp;

        int i = left + 1;
        int j = right;

        /**
         * i == j时有可能arr[i]还没有判断大小,所以不能结束循环
         */
        while (i <= j){

            /**
             * 当左边元素小于arr[left]时继续向前,直到大于等于arr[left]
             */
            if (arr[i].compareTo(arr[left]) < 0){
                i++;
            }

            /**
             * 当右边元素大于arr[left]时不动,直到小于等于arr[left]
             */
            else if (arr[j].compareTo(arr[left]) > 0){
                j--;
            }

            /**
             * 此时两边的元素都不属于两侧,相互调换,直到i >= j
             */
            else {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }

        /**
         * 最后将j处元素和arr[left]互换
         */
        temp = arr[j];
        arr[j] = arr[left];
        arr[left] = temp;

        return j;
    }
}

归并排序法、随机快速排序法和双路快速排序法性能比较

import java.util.Arrays;
import java.util.Random;

public class Algorithm {

    public static void main(String[] args) {

        Integer[] testScale = {10000, 100000};

        for (Integer n : testScale){

            Integer[] randomArr = ArrayGenerator.generatorRandomArray(n, 1);
            Integer[] sortedArr = ArrayGenerator.generatorSortedArray(n, n);

            Integer[] arr1 = Arrays.copyOf(randomArr, randomArr.length);
            Integer[] arr3 = Arrays.copyOf(randomArr, randomArr.length);

            Integer[] arr2 = Arrays.copyOf(sortedArr, sortedArr.length);
            Integer[] arr4 = Arrays.copyOf(sortedArr, sortedArr.length);

            System.out.println("测试随机数组排序性能");
            System.out.println();

            Verify.testTime("MergeSort", randomArr);
            Verify.testTime("QuickSort", arr1);
            Verify.testTime("QuickSort2Ways", arr3);

            System.out.println();

            System.out.println("测试有序数组排序性能");
            System.out.println();

            Verify.testTime("MergeSort", sortedArr);
            Verify.testTime("QuickSort", arr2);
            Verify.testTime("QuickSort2Ways", arr4);

            System.out.println();
        }
    }
}

class QuickSort {

    private QuickSort(){}

    public static<E extends Comparable<E>> void sort2ways(E[] arr){

        Random random = new Random();
        E temp = null;
        sort2ways(arr, 0, arr.length - 1, temp, random);
    }

    public static<E extends Comparable<E>> void sort2ways(E[] arr, int left, int right, E temp, Random random){

        if (left >= right){
            return;
        }

        int p = partition2ways(arr, left, right, temp, random);

        sort2ways(arr, left, p - 1, temp, random);
        sort2ways(arr, p + 1, right, temp, random);
    }

    public static <E extends Comparable<E>> int partition2ways(E[] arr, int left, int right, E temp, Random random){

        int p = random.nextInt(right - left + 1) + left;

        temp = arr[p];
        arr[p] = arr[left];
        arr[left] = temp;

        int i = left + 1;
        int j = right;

        while (i <= j){

            if (arr[i].compareTo(arr[left]) < 0){
                i++;
            }

            else if (arr[j].compareTo(arr[left]) > 0){
                j--;
            }

            else {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }

        temp = arr[j];
        arr[j] = arr[left];
        arr[left] = temp;

        return j;
    }

    public static<E extends Comparable<E>> void sort(E[] arr){

        Random random = new Random();
        E temp = null;
        sort(arr, 0, arr.length - 1, random, temp);
    }

    public static<E extends Comparable<E>> void sort(E[] arr, int left, int right, Random random, E temp){

        if (left >= right){
            return;
        }

        int p = partition(arr, left, right, random, temp);

        sort(arr, left, p - 1, random, temp);
        sort(arr, p + 1, right, random, temp);
    }

    public static <E extends Comparable<E>> int partition(E[] arr, int left, int right, Random random, E temp){

        int p = random.nextInt(right - left + 1) + left;

        temp = arr[p];
        arr[p] = arr[left];
        arr[left] = temp;

        int j = left;

        for (int i = left + 1; i <= right; i++) {

            if (arr[i].compareTo(arr[left]) < 0){

                j++;
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        temp = arr[j];
        arr[j] = arr[left];
        arr[left] = temp;

        return j;
    }
}

class MergeSort {

    private MergeSort(){}

    public static<E extends Comparable<E>> void sort(E[] arr){

        E[] temp = Arrays.copyOf(arr, arr.length);

        sort(arr, 0, arr.length - 1, temp);
    }

    private static<E extends Comparable<E>> void sort(E[] arr, int left, int right, E[] temp){

        if (left >= right){
            return;
        }

        int mid = left + (right - left) / 2;

        sort(arr, left, mid, temp);
        sort(arr, mid + 1, right, temp);

        if (arr[mid].compareTo(arr[mid + 1]) > 0) {
            merge(arr, left, mid, right, temp);
        }
    }

    public static<E extends Comparable<E>> void merge(E[] arr, int left, int mid, int right, E[] temp){

        int i = left;
        int j = mid + 1;

        System.arraycopy(arr, left, temp, left, right - left + 1);

        for (int n = left; n < right + 1; n++) {

            if (i == mid + 1){
                arr[n] = temp[j];
                j++;
            }
            else if (j == right + 1) {
                arr[n] = temp[i];
                i++;
            }
            else if (temp[i].compareTo(temp[j]) <= 0) {
                arr[n] = temp[i];
                i++;
            }
            else{
                arr[n] = temp[j];
                j++;
            }
        }
    }
}

class ArrayGenerator {

    private ArrayGenerator (){}

    public static Integer[] generatorRandomArray (Integer n, Integer maxBound){

        Integer[] arr = new Integer[n];

        Random random = new Random();

        for (int i = 0; i < n; i++) {

            arr[i] = random.nextInt(maxBound);
        }

        return arr;
    }

    public static Integer[] generatorSortedArray (Integer n, Integer maxBound){

        Integer[] arr = new Integer[n];

        for (int i = 0; i < n; i++) {

            arr[i] = i;
        }

        return arr;
    }
}

class Verify {

    private Verify (){}

    public static<E extends Comparable<E>> boolean isSorted(E[] arr){

        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i].compareTo(arr[i + 1]) > 0) {
                return false;
            }
        }

        return true;
    }

    public static<E extends Comparable<E>> void testTime(String AlgorithmName, E[] arr) {

        long startTime = System.nanoTime();

        if (AlgorithmName.equals("MergeSort")) {
            MergeSort.sort(arr);
        }

        if (AlgorithmName.equals("QuickSort")) {
            QuickSort.sort(arr);
        }

        if (AlgorithmName.equals("QuickSort2Ways")) {
            QuickSort.sort2ways(arr);
        }

        long endTime = System.nanoTime();

        if (!Verify.isSorted(arr)){
            throw new RuntimeException(AlgorithmName + "算法排序失败!");
        }

        System.out.println(String.format("%s算法,测试用例为%d,执行时间:%f秒", AlgorithmName, arr.length, (endTime - startTime) / 1000000000.0));
    }
}

快速排序法的复杂度分析

对于普通算法,如果能找到一组数据让它100%变成最坏的情况,那复杂度就看最坏的情况

而对于随机算法,没有一组数据可以让其100%发生性能恶化,因此更严谨的做法是使用期望来计算随机算法的复杂度

普通快速排序法,在数组元素相同时,性能下降概率为100%,因此复杂度为O(n^2)

而双路快速排序法是一个随机算法,它随机选择标定点,虽然在最坏的情况下复杂度为O(n^2),但概率极低。其递归层数期望值为O(logn),复杂度的期望值为O(nlogn)

双路快速排序法还有问题

双路快速排序法,对于元素完全一样的数组,性能得到了很大的提升,但每次拆分成子区间后还是要从头到尾遍历一遍元素,即使这些元素是相等的。

因此,如果可以在第一次遍历的时候,将相等的元素单独区分开,以后不再重复遍历这些元素,也会很好的对性能进行优化。

标签:03,arr,right,temp,int,双路,random,排序,left
来源: https://www.cnblogs.com/taoyuann/p/15442815.html