"""Offline Python algorithm lab for Data Structures Chapter 14 (insertion-sort)."""
import json
VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"
def insertion_sort_shift(arr, left=0, right=None):
a = list(arr)
if right is None:
right = len(a) - 1
comparisons = 0
shifts = 0
for i in range(left + 1, right + 1):
cur = a[i]
j = i - 1
while j >= left:
comparisons += 1
if a[j] > cur:
a[j + 1] = a[j]
shifts += 1
j -= 1
else:
break
a[j + 1] = cur
return a, comparisons, shifts
def insertion_sort_swap(arr):
a = list(arr)
for i in range(len(a)):
for j in range(i, 0, -1):
if a[j] < a[j - 1]:
a[j], a[j - 1] = a[j - 1], a[j]
else:
break
return a
def case_insertion_sort_shift_and_swap():
sample = [64, 34, 25, 12, 22, 11, 90]
nearly = [1, 3, 2, 4, 6, 5, 8, 7]
s_shift, _, _ = insertion_sort_shift(sample)
s_swap = insertion_sort_swap(sample)
n_sorted, n_cmp, n_shf = insertion_sort_shift(nearly)
# 局部区间重载:仅排序索引 1..4
sub_in = [99, 34, 25, 12, 22, 1]
sub_out, _, _ = insertion_sort_shift(sub_in, 1, 4)
expected = {
"shift_sorted": [11, 12, 22, 25, 34, 64, 90],
"swap_matches_shift": True,
"nearly_sorted": [1, 2, 3, 4, 5, 6, 7, 8],
"nearly_shifts": 3,
"subrange_1_to_4": [99, 12, 22, 25, 34, 1],
}
actual = {
"shift_sorted": s_shift,
"swap_matches_shift": s_swap == s_shift,
"nearly_sorted": n_sorted,
"nearly_shifts": n_shf,
"subrange_1_to_4": sub_out,
}
return {
"name": "insertion_sort_shift_and_swap",
"summary": "对比移位版与相邻交换版插入排序,并验证基本有序数组与子区间重载排序",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_insertion_sort_step_trace():
arr = [7, 6, 9, 3, 1]
rounds = []
for i in range(1, len(arr)):
cur = arr[i]
j = i - 1
while j >= 0 and arr[j] > cur:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = cur
rounds.append(list(arr))
expected = {
"round1": [6, 7, 9, 3, 1],
"round2": [6, 7, 9, 3, 1],
"round3": [3, 6, 7, 9, 1],
"round4": [1, 3, 6, 7, 9],
}
actual = {
"round1": rounds[0],
"round2": rounds[1],
"round3": rounds[2],
"round4": rounds[3],
}
return {
"name": "insertion_sort_step_trace",
"summary": "逐步追踪 [7, 6, 9, 3, 1] 四轮插入排序的精确状态变化",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_insertion_sort_best_worst_formula():
n = 10
ordered = list(range(1, n + 1))
reversed_arr = list(range(n, 0, -1))
_, best_cmp, best_shf = insertion_sort_shift(ordered)
_, worst_cmp, worst_shf = insertion_sort_shift(reversed_arr)
# 稳定性验证:相等键不移动(严格 > 条件)
tagged = [(4, "a"), (2, "b"), (4, "c"), (1, "d")]
for i in range(1, len(tagged)):
cur = tagged[i]
j = i - 1
while j >= 0 and tagged[j][0] > cur[0]:
tagged[j + 1] = tagged[j]
j -= 1
tagged[j + 1] = cur
expected = {
"best_comparisons_n_minus_1": n - 1,
"best_shifts": 0,
"worst_comparisons_formula": n * (n - 1) // 2,
"worst_shifts_formula": n * (n - 1) // 2,
"stable_order_for_4": ["a", "c"],
}
actual = {
"best_comparisons_n_minus_1": best_cmp,
"best_shifts": best_shf,
"worst_comparisons_formula": worst_cmp,
"worst_shifts_formula": worst_shf,
"stable_order_for_4": [t for k, t in tagged if k == 4],
}
return {
"name": "insertion_sort_best_worst_formula",
"summary": "验证插入排序最好情况 n-1 次比较、最坏情况 n(n-1)/2 次比较移动公式与稳定性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_insertion_sort_subroutine_and_attachment_audit():
# 验证插入排序作为小区间子过程配合归并排序,并核对离线源码包政策
def hybrid_merge_sort(arr, threshold=8):
if len(arr) <= threshold:
res, _, _ = insertion_sort_shift(arr)
return res
mid = len(arr) // 2
l = hybrid_merge_sort(arr[:mid], threshold)
r = hybrid_merge_sort(arr[mid:], threshold)
out, i, j = [], 0, 0
while i < len(l) and j < len(r):
if l[i] <= r[j]:
out.append(l[i])
i += 1
else:
out.append(r[j])
j += 1
out.extend(l[i:])
out.extend(r[j:])
return out
data = [29, 10, 14, 37, 13, 5, 42, 8, 19, 1, 25, 16, 33, 4, 21, 11]
res = hybrid_merge_sort(data, threshold=6)
attachment_policy = {"offline_no_network_fetch": True, "local_self_contained_lab": True}
expected = {
"hybrid_matches_builtin": True,
"length": 16,
"attachment_offline_policy": True,
}
actual = {
"hybrid_matches_builtin": res == sorted(data),
"length": len(res),
"attachment_offline_policy": attachment_policy["offline_no_network_fetch"] and attachment_policy["local_self_contained_lab"],
}
return {
"name": "insertion_sort_subroutine_and_attachment_audit",
"summary": "验证插入排序作为高阶排序小区间子过程的正确性并登记离线附件策略",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_insertion_sort_shift_and_swap(),
case_insertion_sort_step_trace(),
case_insertion_sort_best_worst_formula(),
case_insertion_sort_subroutine_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-insertion-sort-lab/explore-insertion-sort.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-insertion-sort.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2672.zip