"""Offline Python algorithm lab for Data Structures Chapter 13 (dsa-sorting)."""
import heapq
import json
VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"
def bubble_sort_pairs(items):
a = list(items)
n = len(a)
for i in range(n - 1):
swapped = False
for j in range(0, n - 1 - i):
if a[j][0] > a[j + 1][0]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a
def selection_sort_pairs(items):
a = list(items)
n = len(a)
for i in range(n):
m = i
for j in range(i + 1, n):
if a[j][0] < a[m][0]:
m = j
a[i], a[m] = a[m], a[i]
return a
def insertion_sort_pairs(items):
a = list(items)
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and key[0] < a[j][0]:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
def quick_sort_lomuto(arr):
a = list(arr)
def _qs(lo, hi):
if lo < hi:
pivot = a[hi]
i = lo - 1
for j in range(lo, hi):
if a[j] <= pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[hi] = a[hi], a[i + 1]
pi = i + 1
_qs(lo, pi - 1)
_qs(pi + 1, hi)
_qs(0, len(a) - 1)
return a
def merge_sort_pairs(items):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
left = merge_sort_pairs(items[:mid])
right = merge_sort_pairs(items[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i][0] <= right[j][0]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
def heap_sort(arr):
a = list(arr)
n = len(a)
def sift_down(size, i):
while True:
largest = i
l, r = 2 * i + 1, 2 * i + 2
if l < size and a[l] > a[largest]:
largest = l
if r < size and a[r] > a[largest]:
largest = r
if largest == i:
break
a[i], a[largest] = a[largest], a[i]
i = largest
for i in range(n // 2 - 1, -1, -1):
sift_down(n, i)
for i in range(n - 1, 0, -1):
a[i], a[0] = a[0], a[i]
sift_down(i, 0)
return a
def case_quadratic_sorts_and_stability():
# 使用 [5, 8, 5, 2, 9] 附加原始标签以检验稳定性
tagged = [(5, "first5"), (8, "eight"), (5, "second5"), (2, "two"), (9, "nine")]
b_res = bubble_sort_pairs(tagged)
s_res = selection_sort_pairs(tagged)
i_res = insertion_sort_pairs(tagged)
b_5_order = [t for v, t in b_res if v == 5]
s_5_order = [t for v, t in s_res if v == 5]
i_5_order = [t for v, t in i_res if v == 5]
expected = {
"bubble_sorted_keys": [2, 5, 5, 8, 9],
"bubble_stable": True,
"insertion_stable": True,
"selection_unstable_detected": True,
"selection_5_order": ["second5", "first5"],
}
actual = {
"bubble_sorted_keys": [v for v, _ in b_res],
"bubble_stable": b_5_order == ["first5", "second5"],
"insertion_stable": i_5_order == ["first5", "second5"],
"selection_unstable_detected": s_5_order != ["first5", "second5"],
"selection_5_order": s_5_order,
}
return {
"name": "quadratic_sorts_and_stability",
"summary": "实测冒泡、选择与插入三种 O(n^2) 排序并用重复键 [5,8,5,2,9] 验证稳定性差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nlogn_sorts_quick_merge_heap():
q_res = quick_sort_lomuto([10, 80, 30, 90, 40, 50, 70])
m_in = [(38, "a"), (27, "b"), (43, "c"), (3, "d"), (9, "e"), (27, "f"), (10, "g")]
m_res = merge_sort_pairs(m_in)
h_res = heap_sort([4, 10, 3, 5, 1])
expected = {
"quick_sorted": [10, 30, 40, 50, 70, 80, 90],
"merge_sorted_keys": [3, 9, 10, 27, 27, 38, 43],
"merge_stable_27": ["b", "f"],
"heap_sorted": [1, 3, 4, 5, 10],
}
actual = {
"quick_sorted": q_res,
"merge_sorted_keys": [v for v, _ in m_res],
"merge_stable_27": [t for v, t in m_res if v == 27],
"heap_sorted": h_res,
}
return {
"name": "nlogn_sorts_quick_merge_heap",
"summary": "实测快速排序、稳定归并排序与原地最大堆堆排序三大 O(n log n) 算法",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_bubble_buggy_diagnosis_and_fix():
def bubble_buggy(arr):
a = list(arr)
n = len(a)
for _ in range(n):
for j in range(n - 1):
if a[j] > a[j]: # 恒假 bug
a[j], a[j + 1] = a[j + 1], a[j]
return a
def bubble_fixed_counted(arr):
a = list(arr)
n = len(a)
cmp_cnt = 0
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
cmp_cnt += 1
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a, cmp_cnt
raw = [64, 34, 25, 12, 22, 11, 90]
buggy_out = bubble_buggy(raw)
fixed_out, cmp_cnt = bubble_fixed_counted(raw)
expected = {
"buggy_unchanged": True,
"fixed_sorted": [11, 12, 22, 25, 34, 64, 90],
"fixed_comparisons_le_21": True,
"fixed_comparisons": 21,
}
actual = {
"buggy_unchanged": buggy_out == raw,
"fixed_sorted": fixed_out,
"fixed_comparisons_le_21": cmp_cnt <= 21,
"fixed_comparisons": cmp_cnt,
}
return {
"name": "bubble_buggy_diagnosis_and_fix",
"summary": "复现练习 2 冒泡排序恒假比较 bug 并验证修复及边界收紧优化",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_scenario_selection_and_streaming_topk():
# 场景 4:数据流前 K 个最大元素(维护大小为 K 的最小堆)
stream = [15, 3, 28, 7, 42, 19, 88, 6, 31, 50]
k = 3
min_heap = []
for x in stream:
if len(min_heap) < k:
heapq.heappush(min_heap, x)
elif x > min_heap[0]:
heapq.heapreplace(min_heap, x)
top_k_desc = sorted(min_heap, reverse=True)
# 场景 2:链表归并排序(修改指针 O(1) 辅助节点空间,稳定)
class LNode:
def __init__(self, key, tag, nxt=None):
self.key = key
self.tag = tag
self.next = nxt
def sort_list(head):
if not head or not head.next:
return head
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
l = sort_list(head)
r = sort_list(mid)
dummy = tail = LNode(0, "")
while l and r:
if l.key <= r.key:
tail.next = l
l = l.next
else:
tail.next = r
r = r.next
tail = tail.next
tail.next = l or r
return dummy.next
head = LNode(102, "s1", LNode(101, "s2", LNode(102, "s3", LNode(100, "s4"))))
sh = sort_list(head)
ll_out = []
while sh:
ll_out.append((sh.key, sh.tag))
sh = sh.next
expected = {
"stream_top3": [88, 50, 42],
"linked_list_stable_merge": [(100, "s4"), (101, "s2"), (102, "s1"), (102, "s3")],
}
actual = {
"stream_top3": top_k_desc,
"linked_list_stable_merge": ll_out,
}
return {
"name": "scenario_selection_and_streaming_topk",
"summary": "验证场景选型:链表稳定归并排序与大小 K 最小堆数据流 Top-K 提取",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_quadratic_sorts_and_stability(),
case_nlogn_sorts_quick_merge_heap(),
case_bubble_buggy_diagnosis_and_fix(),
case_scenario_selection_and_streaming_topk(),
]
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-dsa-sorting-lab/explore-dsa-sorting.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-dsa-sorting.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2659.zip