快速排序与快速选择
Quick Sort
快排,排序算法中的一颗明珠。然而在深入了解之后我才学习到其并不是理论上最优秀的排序算法 (最坏情况下需要
规模次数的比较),是排序前的随机打乱赋予了它概率上的性能保证。 除了随机性的应用之外,它的核心思想——partition 也非常的巧妙,能够在不对数组进行完全排序的前提下获得某个元素
a[lo]排序后的准确下标。
Quick sort is practically (NOT empirically) the fastest sorting algorithm. It has three processes:
- Shuffle the array.
- Partition so that, for some
- entry
is in place - No larger entry to the left of
- No smaller entry to the right of
- entry
- Sort each piece recursively.
Partition
Partition is the essence of quick sort. It finally produces an in-place index
To achieve this, we maintain two pointers
- Scan
from left to right so long as a[i] < a[lo]. - Scan
from right to left so long as a[j] > a[lo]. - Exchange
a[i]witha[j].
Repeat until a[lo] with a[j].
See the Java code for partitioning below:
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.
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
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:
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.
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
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
and equal to partition item . - No larger entries to left of
. - No smaller entries to right of
.
To achieve this, we maintain three pointers
Let
a[i] < v: exchangea[lt]witha[i]; increment bothltandia[i] > v: exchangea[gt]witha[i]; decrementgta[i] == v: incrementi
Repeat until
See the Java code for 3-way partitioning below; it's much simpler than traditional one above:
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)
Quick Select
Quick Select 算法实际上应用的是快排中的 partition 思想。找数组第
大的问题居然可以如此优雅的实现,还有着平均线性的优秀时间复杂度,真的令人再次感受到算法的无穷魅力。
The goal of selection problem is, given an array of
A trivial solution is to sort the array, and simply pick the
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
. - No smaller entry to the right of
.
Repeat partitioning in one subarray, depending on
k < j: sethitoj - 1, partitioning the left subarray.k > j: setlotoj + 1, partitioning the right subarray.
finished when a[k].
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
Similar to quicksort, quick-select uses quadratic
Just like we use quicksort as a pratical linearithmic-time algorithm; in most cases, we use quick-select as a pratical linear-time algorithm.
![Partition process in range [lo, hi]](https://cdn.jsdelivr.net/gh/ThisisXXZ/blog-image@affbbaf26495964cc9be9dfb4750a0bd07918234/notes/dsa/algorithm-2-pointers-f37e3e4c6cef.webp)

![3-way partition process in range [lo, hi]](https://cdn.jsdelivr.net/gh/ThisisXXZ/blog-image@affbbaf26495964cc9be9dfb4750a0bd07918234/notes/dsa/algorithm-2-3partition-68cd3e4260a5.webp)