"""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()
本例需在 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。
入口文件:projects/data-structures-random-quick-sort-lab/explore-random-quick-sort.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-random-quick-sort.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2674.zip