随机化快速排序
剖析传统固定枢轴快排在有序/逆序数组上退化至 O(n²) 的根因,详解随机化枢轴选择、Partition 不变量、期望 O(n log n) 递推式,以及三路分区和小数组插入排序优化。
学完这一章,你能够
- 剖析传统固定枢轴快排在有序/逆序数组上退化至 O(n²) 的根因,详解随机化枢轴选择、Partition 不变量、期望 O(n log n) 递推式,以及三路分区和小数组插入排序优化。
传统快排退化根因与随机化改进
快速排序基于分治三步——选基准、分区归位、递归排左右——平均时间复杂度 `O(n log n)`。但传统固定选首/尾元素作枢轴的实现存在明显短板:遇到已排序数组、逆序数组或大量重复元素时,每次分区可能极度偏斜(一边为空、另一边 `n - 1`),导致递归退化为 `O(n²)`。随机化快速排序在每次分区前从当前 `[l..r]` 内等概率随机抽取一个元素与端点交换再作枢轴,把最坏情况从“特定输入必然触发”转化为极低概率事件(理论仅当每次随机都恰取极值,概率低至量级 `1/n!` 级别),从而在任意输入分布下保证期望复杂度 `O(n log n)`。
Partition 核心分区过程与双语言实现
快速排序的核心在于 `Partition`:选定标定点 `v` 后(随机化只需在分区前加入一句 `swap(arr, l, rand(l, r))` 或与末尾 `high` 交换),维护小于区边界指针 `j` 与扫描指针 `i`,遍历完成后把枢轴换到最终切分点,确保左侧全小于(或小于等于)基准、右侧全大于(或大于等于)基准。来源页同时提供了左基准 Java 版与末尾基准 Python 版;历史 Java 源码压缩包离线未下载,本站实测脚本已完成完整对照验证。
递推复杂度分析、两大优化与基准实测
随机化快速排序的耗时递推式为 `T(n) = O(n) + T(k) + T(n - k - 1)`,其中 `O(n)` 为线性分区开销、`k` 为基准左侧元素数、`T(k)` 与 `T(n - k - 1)` 分别对应左右子数组递归耗时。由于枢轴均匀随机选取,`k` 的期望值为 `n/2`,综合所有随机切分的期望时间复杂度为 `E[T(n)] = O(n log n)`,期望递归栈空间 `O(log n)`。
面对实际工程分布,随机化快排常配合两项进阶优化:(1)针对高重复键引入三路分区(划分 `< pivot`、`== pivot`、`> pivot`),跳过等于区递归;(2)当子数组规模小于阈值(通常 `10~20`)时切换为插入排序,消减递归调用常数。本站离线脚本在 `n=150` 有序数组上实测固定枢轴退化至 `11175` 次比较、栈深 `150`,而随机化版本保持低比较与浅栈深;在 400 元素高重复键上实测三路快排比较次数不到单路随机快排的三分之一。来源页面的 KaTeX 公式脚本与多语言代码切换微件均仅作私有留证、绝不执行。
传统固定枢轴快排与随机化快排对比
| 特性 | 传统快速排序 | 随机化快速排序 |
| 最坏时间复杂度 | O(n²) | O(n²)(但实际触发概率极低) |
| 平均/期望时间复杂度 | O(n log n) | O(n log n)(对任意输入期望成立) |
| 最坏情况触发条件 | 固定有序/逆序等特定输入必然触发 | 仅当随机抽样连续命中极值 |
| 空间复杂度 | O(log n)(最坏 O(n) 递归栈) | 期望 O(log n)(递归栈) |
| 稳定性 | 不稳定 | 不稳定 |
实测固定枢轴有序退化 vs 随机化快排、Partition 不变量、三路/小数组优化与四分布基准
展开查看收起
"""Offline Python algorithm lab for Data Structures Chapter 17 (random-quick-sort)."""
import json
import random
VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"
def deterministic_quicksort_last_pivot(arr):
a = list(arr)
stats = {"comps": 0, "max_depth": 0}
def _qs(lo, hi, depth):
if depth > stats["max_depth"]:
stats["max_depth"] = depth
if lo < hi:
pivot = a[hi]
i = lo - 1
for j in range(lo, hi):
stats["comps"] += 1
if a[j] <= pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[hi] = a[hi], a[i + 1]
p = i + 1
_qs(lo, p - 1, depth + 1)
_qs(p + 1, hi, depth + 1)
_qs(0, len(a) - 1, 1)
return a, stats
def randomized_quicksort(arr, seed=42, threshold=1):
a = list(arr)
rng = random.Random(seed)
stats = {"comps": 0, "max_depth": 0}
def insertion(lo, hi):
for i in range(lo + 1, hi + 1):
key = a[i]
j = i - 1
while j >= lo:
stats["comps"] += 1
if a[j] > key:
a[j + 1] = a[j]
j -= 1
else:
break
a[j + 1] = key
def _qs(lo, hi, depth):
if depth > stats["max_depth"]:
stats["max_depth"] = depth
if hi - lo + 1 <= threshold:
if threshold > 1 and lo < hi:
insertion(lo, hi)
return
ridx = rng.randint(lo, hi)
a[ridx], a[hi] = a[hi], a[ridx]
pivot = a[hi]
i = lo - 1
for j in range(lo, hi):
stats["comps"] += 1
if a[j] <= pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[hi] = a[hi], a[i + 1]
p = i + 1
_qs(lo, p - 1, depth + 1)
_qs(p + 1, hi, depth + 1)
if a:
_qs(0, len(a) - 1, 1)
return a, stats
def randomized_3way_quicksort(arr, seed=42):
a = list(arr)
rng = random.Random(seed)
stats = {"comps": 0, "max_depth": 0}
def _qs(lo, hi, depth):
if depth > stats["max_depth"]:
stats["max_depth"] = depth
if lo >= hi:
return
ridx = rng.randint(lo, hi)
a[ridx], a[lo] = a[lo], a[ridx]
pivot = a[lo]
lt, gt, i = lo, hi, lo + 1
while i <= gt:
stats["comps"] += 1
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
_qs(lo, lt - 1, depth + 1)
_qs(gt + 1, hi, depth + 1)
if a:
_qs(0, len(a) - 1, 1)
return a, stats
def case_randomized_quicksort_vs_deterministic_worst():
n = 150
ordered = list(range(n))
s_det, st_det = deterministic_quicksort_last_pivot(ordered)
s_rnd, st_rnd = randomized_quicksort(ordered, seed=2026)
expected = {
"det_worst_comparisons": n * (n - 1) // 2,
"det_linear_recursion_depth": n,
"rnd_matches_sorted": True,
"rnd_much_fewer_comparisons": True,
"rnd_shallow_depth": True,
}
actual = {
"det_worst_comparisons": st_det["comps"],
"det_linear_recursion_depth": st_det["max_depth"],
"rnd_matches_sorted": s_rnd == ordered and s_det == ordered,
"rnd_much_fewer_comparisons": st_rnd["comps"] * 5 < st_det["comps"],
"rnd_shallow_depth": st_rnd["max_depth"] <= 20,
}
return {
"name": "randomized_quicksort_vs_deterministic_worst",
"summary": "在 150 元素有序数组上对比固定枢轴 O(n^2) 退化与随机化快排期望 O(n log n) 表现",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_partition_invariants_check():
# 验证左基准单路分区不变量:arr[l..j-1] < v, arr[j] == v, arr[j+1..r] >= v
a = [4, 6, 2, 3, 1, 5, 7, 8]
l, r = 0, len(a) - 1
v = a[l]
j = l
for i in range(l + 1, r + 1):
if a[i] < v:
j += 1
a[j], a[i] = a[i], a[j]
a[l], a[j] = a[j], a[l]
left_ok = all(x < v for x in a[l:j])
right_ok = all(x >= v for x in a[j + 1 : r + 1])
sample_sorted, _ = randomized_quicksort([3, 6, 8, 10, 1, 2, 1], seed=7)
expected = {
"pivot_value": 4,
"pivot_final_index": 3,
"left_all_lt_pivot": True,
"right_all_ge_pivot": True,
"sample_sorted": [1, 1, 2, 3, 6, 8, 10],
}
actual = {
"pivot_value": a[j],
"pivot_final_index": j,
"left_all_lt_pivot": left_ok,
"right_all_ge_pivot": right_ok,
"sample_sorted": sample_sorted,
}
return {
"name": "partition_invariants_check",
"summary": "校验左基准 Partition 分区前后元素归属不变量及经典样本排序结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_three_way_and_small_subarray_variants():
dup_data = [3, 6, 3, 8, 1, 3, 6, 1]
small_data = [9, 3, 7, 1, 5, 2, 8, 4, 6]
s_3way, _ = randomized_3way_quicksort(dup_data, seed=11)
s_opt, _ = randomized_quicksort(small_data, seed=11, threshold=5)
expected = {
"three_way_sorted": [1, 1, 3, 3, 3, 6, 6, 8],
"small_threshold_sorted": [1, 2, 3, 4, 5, 6, 7, 8, 9],
}
actual = {
"three_way_sorted": s_3way,
"small_threshold_sorted": s_opt,
}
return {
"name": "three_way_and_small_subarray_variants",
"summary": "实测随机化三路快排与小数组切换插入排序两种经典变体优化",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_quicksort_benchmark_and_attachment_audit():
rng = random.Random(17)
size = 400
datasets = {
"random": [rng.randint(0, 10000) for _ in range(size)],
"sorted": list(range(size)),
"reversed": list(range(size, 0, -1)),
"heavy_dup": [rng.randint(0, 5) for _ in range(size)],
}
all_ok = True
dup_1way_comps = dup_3way_comps = 0
for name, data in datasets.items():
ref = sorted(data)
r1, st1 = randomized_quicksort(data, seed=99)
r3, st3 = randomized_3way_quicksort(data, seed=99)
ro, _ = randomized_quicksort(data, seed=99, threshold=10)
if not (r1 == ref and r3 == ref and ro == ref):
all_ok = False
if name == "heavy_dup":
dup_1way_comps = st1["comps"]
dup_3way_comps = st3["comps"]
expected = {
"all_four_distributions_correct": True,
"three_way_beats_single_way_on_heavy_dup": True,
"attachment_offline_only": True,
}
actual = {
"all_four_distributions_correct": all_ok,
"three_way_beats_single_way_on_heavy_dup": dup_3way_comps * 3 < dup_1way_comps,
"attachment_offline_only": True,
}
return {
"name": "quicksort_benchmark_and_attachment_audit",
"summary": "在四类数据分布上基准对照单路/三路/混合随机快排并登记离线附件策略",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_randomized_quicksort_vs_deterministic_worst(),
case_partition_invariants_check(),
case_three_way_and_small_subarray_variants(),
case_quicksort_benchmark_and_attachment_audit(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
单路分区把所有等于枢轴的元素全部归入同一侧(例如全归左侧 `<= pivot` 或全归右侧 `>= pivot`);当数组中大量元素与枢轴相等时,无论随机抽到哪个位置作为枢轴,切分后一侧仍几乎包含全部相等元素,导致递归树严重失衡。