三路排序算法
系统剖析三路快速排序(Three-Way Partitioning)三指针四区不变量、等于区零重复递归优势、全等与高重复键线性级提速实测,以及荷兰国旗颜色分类和学生成绩三段划分实战。
学完这一章,你能够
- 系统剖析三路快速排序(Three-Way Partitioning)三指针四区不变量、等于区零重复递归优势、全等与高重复键线性级提速实测,以及荷兰国旗颜色分类和学生成绩三段划分实战。
三路分区核心思想与适用优势
三路排序算法(Three-Way Partitioning)在双路快排基础上进一步演进:单趟分区把区间划分为 `< v`、`== v`、`> v` 三个明确区域,宛如将红白蓝三色弹珠一次分拣归位。最大突破在于所有等于标定值 `v` 的元素集中停留在中间区域后即永久就位,后续递归只需分别排序 `< v` 与 `> v` 两侧,在处理大量重复键值时能避免海量冗余比较与交换。
三指针四区不变量与逐分支演化
以 `arr[l]`(经随机换入)作为标定值 `v` 的经典三路实现(如参考 Java 版 `QuickSort3Ways`)维护三个边界指针:`lt = l` 使 `arr[l+1..lt] < v`,`gt = r + 1` 使 `arr[gt..r] > v`,扫描指针 `i = l + 1` 使 `arr[lt+1..i) == v`。循环 `while i < gt` 分三种情况处理当前元素 `e = arr[i]`:(1)`e == v` 直接归入等于区,`i++`;(2)`e < v` 将 `e` 与等于区首位 `lt + 1` 交换,随后 `lt++` 且 `i++`;(3)`e > v` 将 `e` 与 `gt - 1` 交换,随后仅 `gt--`(因换回来的新元素尚未检查,`i` 不动)。待 `i == gt` 遍历结束,交换 `arr[l]` 与 `arr[lt]` 后仅递归 `[l..lt-1]` 与 `[gt..r]`。来源 Java 压缩包离线不抓取。
另一种等价的闭区间三指针写法(如 Python 版 `three_way_partition`)令 `lt = low`、`i = low + 1`、`gt = high`,在 `while i <= gt` 中遇 `arr[i] < pivot` 直接交换 `arr[lt]` 与 `arr[i]` 并同时递增 `lt, i`(自然把枢轴推着向右滑过 `< pivot` 区),遇 `arr[i] > pivot` 交换 `arr[i]` 与 `arr[gt]` 并递减 `gt`,遇相等则 `i += 1`;循环退出后直接返回等于区闭区间 `(lt, gt)`,随后递归 `(low, lt - 1)` 与 `(gt + 1, high)`,无需最后额外交换枢轴。
经典实战应用与复杂度分析
三路分区不仅是排序利器,还直接对应两类经典原地分拣问题:示例 1 荷兰国旗颜色排序(`0=红, 1=白, 2=蓝`)以 `red_ptr`、`white_ptr`、`blue_ptr` 单趟 `O(n)` 时间、`O(1)` 空间将 `[2,0,2,1,1,0,1,2,0,1,0,2]` 原地整理为 `[0,0,0,0,1,1,1,1,2,2,2,2]`;示例 2 学生成绩三段划分以 `60` 与 `80` 为双阈值将 `[45,78,92,56,85,67,72,88,59,95,61,73]` 一趟原地划分为不及格(`<60`)、良好(`60~80`)与优秀(`>80`)三段。
时间递推式可写为 `T(n) = O(n) + T(k) + T(n - k - m)`(`m` 为等于枢轴的元素个数)。当全数组元素相同时 `m = n`,仅一趟 `n - 1` 次比较即完成排序,退化为极优的 `O(n)`;一般随机数据平均仍为 `O(n log n)`,极端不均最坏 `O(n²)`;递归栈空间最佳 `O(log n)`、最坏 `O(n)`(可通过尾递归消除或显式栈迭代优化)。本站脚本在 500 元素全等及 4 键值重复数据集上实测三路快排调用与比较次数显著优于双路快排。来源页底多语言切换脚本仅作私有留存、不执行。
传统快速排序与三路快速排序对比
| 特性 | 传统快速排序 | 三路快速排序 |
| 分区数量 | 2 个区(小于基准、大于基准) | 3 个区(小于、等于、大于基准) |
| 处理重复元素 | 效率较低,重复元素反复参与递归比较 | 效率极高,相等键一次聚拢不再递归 |
| 时间复杂度 | 平均 O(n log n),最坏 O(n²) | 平均 O(n log n),高重复趋近 O(n),最坏 O(n²) |
| 空间复杂度 | 期望 O(log n)(递归栈) | 期望 O(log n)(递归栈) |
| 适用场景 | 元素基本唯一或低重复率的通用排序 | 高重复键值、颜色分类、分段归类 |
实测三路分区不变量、全等/高重复键线性提速、荷兰国旗颜色排序与成绩分段
展开查看收起
"""Offline Python algorithm lab for Data Structures Chapter 19 (3way-qiuck-sort)."""
import json
import random
VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"
def three_way_partition(arr, low, high, rng=None, stats=None):
if rng is not None:
ridx = rng.randint(low, high)
arr[low], arr[ridx] = arr[ridx], arr[low]
pivot = arr[low]
lt, i, gt = low, low + 1, high
while i <= gt:
if stats is not None:
stats["comps"] += 1
if arr[i] < pivot:
arr[lt], arr[i] = arr[i], arr[lt]
lt += 1
i += 1
elif arr[i] > pivot:
arr[i], arr[gt] = arr[gt], arr[i]
gt -= 1
else:
i += 1
return lt, gt
def three_way_quicksort(arr, seed=42):
a = list(arr)
rng = random.Random(seed)
stats = {"comps": 0, "calls": 0, "max_depth": 0}
def _qs(lo, hi, depth):
stats["calls"] += 1
if depth > stats["max_depth"]:
stats["max_depth"] = depth
if lo >= hi:
return
lt, gt = three_way_partition(a, lo, hi, rng=rng, stats=stats)
_qs(lo, lt - 1, depth + 1)
_qs(gt + 1, hi, depth + 1)
if a:
_qs(0, len(a) - 1, 1)
return a, stats
def two_way_quicksort_counted(arr, seed=42):
a = list(arr)
rng = random.Random(seed)
stats = {"comps": 0, "calls": 0}
def _qs(l, r):
stats["calls"] += 1
if l >= r:
return
ridx = rng.randint(l, r)
a[l], a[ridx] = a[ridx], a[l]
v = a[l]
i, j = l + 1, r
while True:
while i <= r:
stats["comps"] += 1
if a[i] < v:
i += 1
else:
break
while j >= l + 1:
stats["comps"] += 1
if a[j] > v:
j -= 1
else:
break
if i > j:
break
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
a[l], a[j] = a[j], a[l]
_qs(l, j - 1)
_qs(j + 1, r)
if a:
_qs(0, len(a) - 1)
return a, stats
def case_three_way_partition_and_quicksort():
a = [5, 2, 5, 8, 1, 5, 9, 3, 5]
pivot = a[0]
lt, gt = three_way_partition(a, 0, len(a) - 1, rng=None)
lt_ok = all(x < pivot for x in a[:lt])
eq_ok = all(x == pivot for x in a[lt : gt + 1])
gt_ok = all(x > pivot for x in a[gt + 1 :])
full_sorted, _ = three_way_quicksort([5, 2, 5, 8, 1, 5, 9, 3, 5], seed=19)
expected = {
"eq_range_len": 4,
"lt_zone_valid": True,
"eq_zone_valid": True,
"gt_zone_valid": True,
"full_sorted": [1, 2, 3, 5, 5, 5, 5, 8, 9],
}
actual = {
"eq_range_len": gt - lt + 1,
"lt_zone_valid": lt_ok,
"eq_zone_valid": eq_ok,
"gt_zone_valid": gt_ok,
"full_sorted": full_sorted,
}
return {
"name": "three_way_partition_and_quicksort",
"summary": "验证三路分区 <v / ==v / >v 三区不变量与完整三路快速排序结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_three_way_duplicates_linear_speedup():
all_eq = [7] * 500
s_eq, st_eq = three_way_quicksort(all_eq, seed=19)
rng = random.Random(19)
heavy_dup = [rng.randint(1, 4) for _ in range(500)]
ref = sorted(heavy_dup)
s3, st3 = three_way_quicksort(heavy_dup, seed=19)
s2, st2 = two_way_quicksort_counted(heavy_dup, seed=19)
expected = {
"all_equal_sorted": True,
"all_equal_single_pass_comps": 499,
"all_equal_max_depth": 2,
"heavy_dup_both_correct": True,
"three_way_fewer_comps_than_two_way": True,
"three_way_fewer_calls_than_two_way": True,
}
actual = {
"all_equal_sorted": s_eq == all_eq,
"all_equal_single_pass_comps": st_eq["comps"],
"all_equal_max_depth": st_eq["max_depth"],
"heavy_dup_both_correct": s3 == ref and s2 == ref,
"three_way_fewer_comps_than_two_way": st3["comps"] * 2 < st2["comps"],
"three_way_fewer_calls_than_two_way": st3["calls"] * 10 < st2["calls"],
}
return {
"name": "three_way_duplicates_linear_speedup",
"summary": "量化对比全等与 4 键值 500 元素数组上三路快排相比双路快排的线性级加速",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dutch_national_flag_colors():
colors = [2, 0, 2, 1, 1, 0, 1, 2, 0, 1, 0, 2]
red, white, blue = 0, 0, len(colors) - 1
while white <= blue:
if colors[white] == 0:
colors[red], colors[white] = colors[white], colors[red]
red += 1
white += 1
elif colors[white] == 1:
white += 1
else:
colors[white], colors[blue] = colors[blue], colors[white]
blue -= 1
expected = {"sorted_colors": [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]}
actual = {"sorted_colors": colors}
return {
"name": "dutch_national_flag_colors",
"summary": "实测荷兰国旗颜色排序(0=红、1=白、2=蓝)单趟原地三指针分拣",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_grade_segmentation_and_attachment_audit():
scores = [45, 78, 92, 56, 85, 67, 72, 88, 59, 95, 61, 73]
low, mid, high = 0, 0, len(scores) - 1
while mid <= high:
if scores[mid] < 60:
scores[low], scores[mid] = scores[mid], scores[low]
low += 1
mid += 1
elif scores[mid] <= 80:
mid += 1
else:
scores[mid], scores[high] = scores[high], scores[mid]
high -= 1
fail_part = scores[:low]
good_part = scores[low : high + 1]
exc_part = scores[high + 1 :]
expected = {
"fail_count": 3,
"good_count": 5,
"excellent_count": 4,
"fail_all_lt_60": True,
"good_all_60_to_80": True,
"excellent_all_gt_80": True,
"attachment_offline_only": True,
}
actual = {
"fail_count": len(fail_part),
"good_count": len(good_part),
"excellent_count": len(exc_part),
"fail_all_lt_60": all(s < 60 for s in fail_part),
"good_all_60_to_80": all(60 <= s <= 80 for s in good_part),
"excellent_all_gt_80": all(s > 80 for s in exc_part),
"attachment_offline_only": True,
}
return {
"name": "grade_segmentation_and_attachment_audit",
"summary": "实测三路分区学生成绩分段(<60、60~80、>80)并登记来源源码包离线策略",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_three_way_partition_and_quicksort(),
case_three_way_duplicates_linear_speedup(),
case_dutch_national_flag_colors(),
case_grade_segmentation_and_attachment_audit(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 `lt` 左侧换到 `i` 位置的元素必然来自已扫描过的等于基准区域(值为 `pivot`),无需复检可直接 `i++`;而从 `gt` 右端换到 `i` 位置的元素此前从未检查过,必须原地留待下一轮继续判定。