快速排序与快速选择

Quick Sort

快排,排序算法中的一颗明珠。然而在深入了解之后我才学习到其并不是理论上最优秀的排序算法 (最坏情况下需要 N2N^2 规模次数的比较),是排序前的随机打乱赋予了它概率上的性能保证。

除了随机性的应用之外,它的核心思想——partition 也非常的巧妙,能够在不对数组进行完全排序的前提下获得某个元素 a[lo] 排序后的准确下标 jj。

Quick sort is practically (NOT empirically) the fastest sorting algorithm. It has three processes:

  • Shuffle the array.
  • Partition so that, for some jj
    • entry aja_j is in place
    • No larger entry to the left of jj
    • No smaller entry to the right of jj
  • Sort each piece recursively.

Partition

Partition is the essence of quick sort. It finally produces an in-place index jj so that no larger entry to the left of jj and no smaller entry to the right of jj.

To achieve this, we maintain two pointers ii and jj as follows:

  • Scan ii from left to right so long as a[i] < a[lo].
  • Scan jj from right to left so long as a[j] > a[lo].
  • Exchange a[i] with a[j].

Repeat until ii and jj pointers cross. When it happens, exchange a[lo] with a[j].

Partition process in range [lo, hi]

See the Java code for partitioning below:

java
private static int partition(Comparable[] a, int lo, int hi) {
    int i = lo, j = hi + 1;
    while (true) {
        while (less(a[++i], a[lo]))	// stop on equal keys
            if (i == hi)	break;
        while (less(a[lo], a[--j]))	// stop on equal keys
            if (j == lo)	break;
        if (i >= j)	break;
        exch(a, i, j);
    }
    exch(a, lo, j);	 // now j is in place with the partitioning item a[lo]
    return j;
}

Counter-intuitively, when duplicates are present, it is better to stop on keys equal to the partitioning item's key.

stop on equal keys: uses  instead of  in the condition

Considering an array with all entries having the same key; in this case, algorithm goes quadratic unless partitioning stops on equal keys.

Stopping on equal keys guarantees ∼Nlg⁡N\sim N\lg{N} compares when all keys are equal.

However, a more desirable consequence should be that all items equal to the partitioning item are in place. Stay tuned for the 3-way partitioning technique.

Shuffle

Randomly shuffling the array probabilistically guarantee against the worst case.

The worst case happens when the array is sorted (key is already in order). This will cost quadratic number of compares: N+(N−1)+...+1∼12N2N+(N-1)+...+1\sim \frac{1}{2}N^2.

However, giving the array a random shuffle could make the probability of the worst case happening negligible. It is based on a math model that can be validated with experiments.

java
public class Quick {
    private static int partition(Comparable[] a, int lo, int hi) 
    { /* see previous partition code */ }
    
    public static void sort(Comparable[] a) {
        StdRandom.shuffle(a);
        sort(a, 0, a.length - 1);
    }
    
    private static void sort(Comparable[] a, int lo, int hi) {
        if (hi <= lo)	return;
        int j = partition(a, lo, hi);
        sort(a, lo, j - 1);
        sort(a, j + 1, hi);
    }
}

The average number of compares to quicksort an array of NN distinct keys is ∼1.39Nlg⁡N\sim 1.39N\lg{N}, and the average number of exchange is ∼13Nlg⁡N\sim \frac{1}{3}N\lg N.

Though quicksort has 39% more compares than mergesort, it is faster in practice because of less data movement.

3-way Partitioning

3-way partitioning (3-way quicksort) improves traditional quicksort in presence of duplicate keys.

  • It put all items equal to the partitioning item in place.
  • It reduces running time from linearithmic to linear in broad class of applications.

3-way quicksort partition array into three parts that:

  • Entries between ltlt and gtgt equal to partition item vv.
  • No larger entries to left of ltlt.
  • No smaller entries to right of gtgt.

To achieve this, we maintain three pointers ltlt, gtgt, and ii as follows:

Let vv be partitioning item aloa_{lo}, scanning ii from left to right.

  • a[i] < v: exchange a[lt] with a[i]; increment both lt and i
  • a[i] > v: exchange a[gt] with a[i]; decrement gt
  • a[i] == v: increment i

Repeat until ii and gtgt pointers cross.

3-way partition process in range [lo, hi]

See the Java code for 3-way partitioning below; it's much simpler than traditional one above:

java
private static void sort(Comparable[] a, int lo, int hi) {
    if (hi <= lo)	return;
    int lt = lo, gt = hi;
    Comparable v = a[lo];
    int i = lo;
    while (i <= gt) {
        int cmp = a[i].compareTo(v);
        if      (cmp < 0)	exch(a, lt++, i++);
        else if (cmp > 0)	exch(a, i, gt--);
        else             	i++; 
    }
    sort(a, lo, lt - 1);
    sort(a, gt + 1, hi);
}

It is proven that 3-way quick sort needs only (linear) NN compares when in best case, but it still needs (quadratic) 12N2\frac{1}{2}N^2 compares in worst case.

Quick Select

Quick Select 算法实际上应用的是快排中的 partition 思想。找数组第 kk 大的问题居然可以如此优雅的实现,还有着平均线性的优秀时间复杂度,真的令人再次感受到算法的无穷魅力。

The goal of selection problem is, given an array of NN items, find the kk-th smallest item.

A trivial solution is to sort the array, and simply pick the kk-th item. It means we find a Nlog⁡NN\log N upper bound for this problem. However, is selection as hard as sorting?

In fact, there is a linear-time quick-select algorithm: we partition the array so that,

  • Entry a[j] is in place.
  • No larger entry to the left of jj.
  • No smaller entry to the right of jj.

Repeat partitioning in one subarray, depending on jj;

  • k < j: set hi to j - 1, partitioning the left subarray.
  • k > j: set lo to j + 1, partitioning the right subarray.

finished when jj equals kk, return a[k].

java
public static Comparable select(Comparable[] a, int k) {
    StdRandom.shuffle(a);
    int lo = 0, hi = a.length - 1;
    while (hi > lo) {
        int j = partition(a, lo, hi);
        if (k > j)       lo = j + 1;
        else if (k < j)  hi = j - 1;
        else             return a[k];
    }
    return a[k];
}

Proposition. Quick-select takes linear time on average.

Intuitively, each partitioning step splits the array approximately in half: the total number of compares will be N+N/2+N/4+...+1∼2NN+N/2+N/4+...+1\sim 2N. The formal analysis is similar to quicksort.

Similar to quicksort, quick-select uses quadratic ∼1/2N2\sim 1/2N^2 compares in the worst case, but the random shuffle provides a probabilistic guarantee.

Just like we use quicksort as a pratical linearithmic-time algorithm; in most cases, we use quick-select as a pratical linear-time algorithm.

CC BY-NC-SA 4.0
正在加载评论…