快速排序的思路
1 | algorithm quicksort(A, lo, hi) is |
快速排序的partition方式
一种是Lomuto partition scheme,另外一种是Hoare partition scheme。
Lomuto partition
This scheme is attributed to Nico Lomuto and popularized by Bentley in his book
lomuto的partition实现方式
i指示最前面的大于pivot的元素位置,j从前往后滑动来调整元素位置。每次j碰到小于pivot的元素,则swap i位置的元素和j位置的元素,再i指向下一个大于pivot的元素。
最后,记得swap i位置的元素和最末尾的元素。
1 | private int lomutoPartition(int nums[], int lo, int hi) { |
Hoare partition scheme
The original partition scheme described by C.A.R. Hoare uses two indices that start at the ends of the array being partitioned, then move toward each other, until they detect an inversion.
Hoare’s scheme is more efficient than Lomuto’s partition scheme because it does three times fewer swaps on average, and it creates efficient partitions even when all values are equal.
hoare的partition实现方式
i从前往后找到大于pivot的元素,j从后往前找到小于pivot的元素,然后两者swap.
1 | private int hoarePartition(int nums[], int lo, int hi) { |