史上最易理解的快速排序原理详解以及Arrays.sort方法

Arrays.sort()方法可以通过源码发现内部使用的是快速排序,然后我们探索一下快速排序的原理

快速排序简介

快速排序是交换排序的一种,交换排序的含义是根据序列中的两个元素关键字的比较结果来交换两个记录在序列中的位置。同时,冒泡排序(时间复杂度为O(n2))作为交换排序中的经典,快速排序也是对冒泡排序的一种改进。
快速排序是所有内部排序算法性能最优的排序算法,但是它是一个不稳定的排序算法。

快速排序步骤

  1. 选择基准元素
  2. 通过一趟排序将待排序的记录分割成独立的两部分,其中一部分比基准元素大,另一部分比基准元素小
  3. 基准元素在其排好序的位置上
  4. 分别对划分好的两部分继续进行快速排序,直到整个序列有序

举个栗子:
我们对序列 9 11 5* 22 18 7 5 36 进行非递减排序

在这里插入图片描述在这里插入图片描述 在这里插入图片描述

快速排序性能分析

平均时间为Tavg(n) = kn ln n,其中n为待排序序列中记录的个数,k为某个常数,在所有同类数量级的此类排序方法中,快速排序的常数因子k最小。
空间复杂度,最坏的情况下O(n),就是每个数字都作为一次基准,平均情况是O(nlog2n)
时间复杂度,在很大程度上取决于划分算法与序列本身的情况,平均的时间复杂度为O(nlog2n)。
在未改进的情况下,若初始记录序列按照关键字有序或基本有序时,快速排序会退化为冒泡排序,时间复杂度为O(n2)。

快速排序代码实现

public class QuickSort {
    /**
     * 划分算法
     * @param arr
     * @param low
     * @param high
     * @return
     */
    public static int Partition(int[] arr, int low, int high){
        //交换数组中的low和high位置的记录,并返回其所在位置
        //在它之前或之后的记录均不大于或小于它
        arr[0] = arr[low];
        int pivotkey = arr[low];
        //直到low与high重合,循环结束
        while (low < high){
            //高位指针向左移动
            while (low < high && arr[high] >= pivotkey)
                --high;
            arr[low] = arr[high];//赋值
            //低位指针向右移动
            while (low < high && arr[high] <= pivotkey)
                ++low;
            arr[high] = arr[low];//赋值
        }
        arr[low] = arr[0];
        return low;
    }

    /**
     * 排序算法
     * @param arr
     * @param low
     * @param high
     */
    public static void Qsort(int[] arr, int low, int high){
        //长度大于1
        if (low < high){
            int pivotloc = Partition(arr, low, high);//划分
            Qsort(arr, low,pivotloc-1);//低子表递归排序
            Qsort(arr, pivotloc+1, high);//高子表递归排序
        }
    }
    public static void main(String[] args) {
        int[] array = new int[]{0,49,38,65,97,76,13,27,49};
        for (int i = 1; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
        Qsort(array,1,8);
        for (int i = 1; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}

运行结果截图
在这里插入图片描述

快速排序改进

通常使用“三者取中”的法则来选取枢轴记录,即比较a[start]、a[end]、a[(start+end)/2],取三者取中值记录为枢轴,采用这种方法能够大大改善快去排序在最坏情况下的性能。

Arrays.sort()方法源码

附源码:

    public static void sort(int[] a) {
        DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
    }
         /**
         * Sorts the specified range of the array using the given
         * workspace array slice if possible for merging
         *
         * @param a the array to be sorted
         * @param left the index of the first element, inclusive, to be sorted
         * @param right the index of the last element, inclusive, to be sorted
         * @param work a workspace array (slice)
         * @param workBase origin of usable space in work array
         * @param workLen usable size of work array
         */
    static void sort(int[] a, int left, int right,
                         int[] work, int workBase, int workLen) {
            // Use Quicksort on small arrays
            if (right - left < QUICKSORT_THRESHOLD) {
                sort(a, left, right, true);
                return;
            }
    
            /*
             * Index run[i] is the start of i-th run
             * (ascending or descending sequence).
             */
            int[] run = new int[MAX_RUN_COUNT + 1];
            int count = 0; run[0] = left;
    
            // Check if the array is nearly sorted
            for (int k = left; k < right; run[count] = k) {
                if (a[k] < a[k + 1]) { // ascending
                    while (++k <= right && a[k - 1] <= a[k]);
                } else if (a[k] > a[k + 1]) { // descending
                    while (++k <= right && a[k - 1] >= a[k]);
                    for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
                        int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
                    }
                } else { // equal
                    for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {
                        if (--m == 0) {
                            sort(a, left, right, true);
                            return;
                        }
                    }
                }
    
                /*
                 * The array is not highly structured,
                 * use Quicksort instead of merge sort.
                 */
                if (++count == MAX_RUN_COUNT) {
                    sort(a, left, right, true);
                    return;
                }
            }
    
            // Check special cases
            // Implementation note: variable "right" is increased by 1.
            if (run[count] == right++) { // The last run contains one element
                run[++count] = right;
            } else if (count == 1) { // The array is already sorted
                return;
            }
    
            // Determine alternation base for merge
            byte odd = 0;
            for (int n = 1; (n <<= 1) < count; odd ^= 1);
    
            // Use or create temporary array b for merging
            int[] b;                 // temp array; alternates with a
            int ao, bo;              // array offsets from 'left'
            int blen = right - left; // space needed for b
            if (work == null || workLen < blen || workBase + blen > work.length) {
                work = new int[blen];
                workBase = 0;
            }
            if (odd == 0) {
                System.arraycopy(a, left, work, workBase, blen);
                b = a;
                bo = 0;
                a = work;
                ao = workBase - left;
            } else {
                b = work;
                ao = 0;
                bo = workBase - left;
            }
    
            // Merging
            for (int last; count > 1; count = last) {
                for (int k = (last = 0) + 2; k <= count; k += 2) {
                    int hi = run[k], mi = run[k - 1];
                    for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {
                        if (q >= hi || p < mi && a[p + ao] <= a[q + ao]) {
                            b[i + bo] = a[p++ + ao];
                        } else {
                            b[i + bo] = a[q++ + ao];
                        }
                    }
                    run[++last] = hi;
                }
                if ((count & 1) != 0) {
                    for (int i = right, lo = run[count - 1]; --i >= lo;
                        b[i + bo] = a[i + ao]
                    );
                    run[++last] = right;
                }
                int[] t = a; a = b; b = t;
                int o = ao; ao = bo; bo = o;
            }
        }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值