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