"""Offline Python algorithm lab for Data Structures Chapter 18 (2way-quick-sort)."""
import json
import random
VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"
def two_way_partition(arr, l, r, rng=None, stats=None):
if rng is not None:
ridx = rng.randint(l, r)
arr[l], arr[ridx] = arr[ridx], arr[l]
v = arr[l]
i, j = l + 1, r
while True:
while i <= r:
if stats is not None:
stats["comps"] += 1
if arr[i] < v:
i += 1
else:
break
while j >= l + 1:
if stats is not None:
stats["comps"] += 1
if arr[j] > v:
j -= 1
else:
break
if i > j:
break
arr[i], arr[j] = arr[j], arr[i]
i += 1
j -= 1
arr[l], arr[j] = arr[j], arr[l]
return j
def two_way_quicksort(arr, seed=42):
a = list(arr)
rng = random.Random(seed)
stats = {"comps": 0, "max_depth": 0}
def _qs(l, r, depth):
if depth > stats["max_depth"]:
stats["max_depth"] = depth
if l >= r:
return
p = two_way_partition(a, l, r, rng=rng, stats=stats)
_qs(l, p - 1, depth + 1)
_qs(p + 1, r, depth + 1)
if len(a) >= 2:
_qs(0, len(a) - 1, 1)
return a, stats
def single_way_random_quicksort(arr, seed=42):
a = list(arr)
rng = random.Random(seed)
stats = {"comps": 0, "max_depth": 0}
def _qs(l, r, depth):
if depth > stats["max_depth"]:
stats["max_depth"] = depth
if l >= r:
return
ridx = rng.randint(l, r)
a[l], a[ridx] = a[ridx], a[l]
v = a[l]
j = l
for i in range(l + 1, r + 1):
stats["comps"] += 1
if a[i] < v:
j += 1
a[j], a[i] = a[i], a[j]
a[l], a[j] = a[j], a[l]
_qs(l, j - 1, depth + 1)
_qs(j + 1, r, depth + 1)
if len(a) >= 2:
_qs(0, len(a) - 1, 1)
return a, stats
def case_two_way_partition_invariants():
a = [4, 2, 2, 8, 3, 3, 1, 5, 3, 2]
pivot = a[0]
p = two_way_partition(a, 0, len(a) - 1, rng=None)
left_ok = all(x <= pivot for x in a[:p])
right_ok = all(x >= pivot for x in a[p + 1 :])
expected = {
"pivot_at_p": 4,
"left_all_le_pivot": True,
"right_all_ge_pivot": True,
}
actual = {
"pivot_at_p": a[p],
"left_all_le_pivot": left_ok,
"right_all_ge_pivot": right_ok,
}
return {
"name": "two_way_partition_invariants",
"summary": "验证双路分区后 arr[left..p-1] <= pivot、arr[p] == pivot 与 arr[p+1..right] >= pivot 不变量",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_two_way_vs_single_way_duplicates():
rng = random.Random(18)
dup = [rng.randint(0, 2) for _ in range(300)]
ref = sorted(dup)
s1, st1 = single_way_random_quicksort(dup, seed=18)
s2, st2 = two_way_quicksort(dup, seed=18)
expected = {
"both_match_sorted": True,
"two_way_fewer_comparisons": True,
"two_way_much_shallower_stack": True,
}
actual = {
"both_match_sorted": s1 == ref and s2 == ref,
"two_way_fewer_comparisons": st2["comps"] * 2 < st1["comps"],
"two_way_much_shallower_stack": st2["max_depth"] * 3 < st1["max_depth"],
}
return {
"name": "two_way_vs_single_way_duplicates",
"summary": "在 300 元素高重复数组上对比单路快排退化与双路快排均衡切分优势",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_two_way_sort_examples_and_instability():
arr1 = [4, 2, 2, 8, 3, 3, 1, 5, 3, 2]
s1, _ = two_way_quicksort(arr1, seed=2026)
rng = random.Random(99)
arr2 = [rng.randint(0, 49) for _ in range(20)]
s2, _ = two_way_quicksort(arr2, seed=2026)
# 构造固定枢轴双路分区证明不稳定性:[(3,'a'), (3,'b'), (1,'c')]
tagged = [(3, "a"), (3, "b"), (1, "c")]
v = tagged[0][0]
i, j = 1, 2
while True:
while i <= 2 and tagged[i][0] < v:
i += 1
while j >= 1 and tagged[j][0] > v:
j -= 1
if i > j:
break
tagged[i], tagged[j] = tagged[j], tagged[i]
i += 1
j -= 1
tagged[0], tagged[j] = tagged[j], tagged[0]
# tagged 变为 [(1,'c'), (3,'a'), (3,'b')] 或反序,改用 [(2,'a'), (3,'x'), (2,'b'), (1,'y')]
t2 = [(2, "a"), (2, "b"), (2, "c")]
# 对全 2 数组双路分区一次:i=1 停在 (2,'b'), j=2 停在 (2,'c'),交换得 [(2,'a'), (2,'c'), (2,'b')],再换 l=0 与 j=1 得 [(2,'c'), (2,'a'), (2,'b')]
v2 = t2[0][0]
i, j = 1, 2
while True:
while i <= 2 and t2[i][0] < v2:
i += 1
while j >= 1 and t2[j][0] > v2:
j -= 1
if i > j:
break
t2[i], t2[j] = t2[j], t2[i]
i += 1
j -= 1
t2[0], t2[j] = t2[j], t2[0]
expected = {
"arr1_sorted": [1, 2, 2, 2, 3, 3, 3, 4, 5, 8],
"arr2_matches_builtin": True,
"instability_witness_order": ["c", "a", "b"],
"is_unstable": True,
}
actual = {
"arr1_sorted": s1,
"arr2_matches_builtin": s2 == sorted(arr2),
"instability_witness_order": [tag for _, tag in t2],
"is_unstable": [tag for _, tag in t2] != ["a", "b", "c"],
}
return {
"name": "two_way_sort_examples_and_instability",
"summary": "实测重复元素数组排序正确性并构造相等键交换反例证实双路快排不稳定",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_two_way_attachment_and_edges_audit():
# 全等数组双路分区近似中点切分,不会退化
all_eq = [7] * 64
p = two_way_partition(list(all_eq), 0, len(all_eq) - 1, rng=None)
s_eq, st_eq = two_way_quicksort(all_eq, seed=7)
s_empty, _ = two_way_quicksort([], seed=7)
s_one, _ = two_way_quicksort([9], seed=7)
expected = {
"all_equal_partition_midpoint": 31,
"all_equal_depth_le_10": True,
"all_equal_sorted_ok": True,
"edge_empty_one": [[], [9]],
"attachment_offline_only": True,
}
actual = {
"all_equal_partition_midpoint": p,
"all_equal_depth_le_10": st_eq["max_depth"] <= 10,
"all_equal_sorted_ok": s_eq == all_eq,
"edge_empty_one": [s_empty, s_one],
"attachment_offline_only": True,
}
return {
"name": "two_way_attachment_and_edges_audit",
"summary": "验证全等数组双路对半切分、空/单元素边界及来源源码包离线策略",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_two_way_partition_invariants(),
case_two_way_vs_single_way_duplicates(),
case_two_way_sort_examples_and_instability(),
case_two_way_attachment_and_edges_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-2way-quick-sort-lab/explore-2way-quick-sort.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-2way-quick-sort.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2639.zip