插入排序
深入剖析直接插入排序构建有序前缀的工作原理、逐步演示轨迹、移位赋值与相邻交换双实现、最好 O(n) 与最坏 n(n-1)/2 公式推导,以及作为高阶排序子过程的工程价值。
学完这一章,你能够
- 深入剖析直接插入排序构建有序前缀的工作原理、逐步演示轨迹、移位赋值与相邻交换双实现、最好 O(n) 与最坏 n(n-1)/2 公式推导,以及作为高阶排序子过程的工程价值。
工作原理与有序度敏感特性
插入排序(Insertion Sort,又称直接插入排序)将数组逻辑划分为左侧已排序区(初始仅含首元素)与右侧未排序区,外层循环依次取出未排序首元素,内层循环向左扫描已排序区找到合适位置插入,使有序区长度逐轮加一。其平均与最坏时间复杂度为 `O(n²)`、空间复杂度为 `O(1)`,且耗时强烈依赖数组初始有序度:完全有序时每轮仅比较前邻即止,总共只需 `n - 1` 次比较(`O(n)`);完全逆序时比较与移动达最大。
过程演示与双语言移位/交换实现
以升序排列 `[7, 6, 9, 3, 1]` 为例:第一轮 `6 < 7` 移至 `7` 前得 `[6, 7, 9, 3, 1]`;第二轮 `9 >= 7` 无需移动;第三轮 `3` 依次越过 `9, 7, 6` 插入最前得 `[3, 6, 7, 9, 1]`;第四轮 `1` 插入队首最终有序 `[1, 3, 6, 7, 9]`。
编码实现存在两种常见写法:其一是相邻交换版(发现 `arr[j] < arr[j-1]` 即交换,否则 `break`);其二是工程更推荐的移位赋值版——先将 `current_value = arr[i]` 暂存,内层凡遇 `arr[j] > current_value` 仅做一次单向后移 `arr[j+1] = arr[j]`,循环退出后再一次性写入 `arr[j+1] = current_value`,将每次移动的三次赋值缩减为一次,并可扩展支持局部区间 `[left, right]` 重载供快速排序或归并排序调用。来源页面附带的历史 Java 源码压缩包受离线与停采约束未请求下载,本站离线脚本已提供完整自包含实测。
复杂度推导、稳定性与多语言对照说明
在最坏情况(数组完全逆序)下,第 1 个元素比较 `0` 次,第 2 个元素比较并移动 `1` 次,直至第 `n` 个元素比较并移动 `n - 1` 次,总计 `0 + 1 + 2 + ... + (n - 1) = n(n - 1)/2` 次,即 `O(n²)`。由于仅在严格大于(`arr[j] > current_value`)时后移元素,相等元素相对次序绝对保持稳定。来源页面底部通过客户端脚本渲染多语言代码示例切换面板,本站不执行来源脚本,聚焦核心算法原理与离线可运行 Python 实测。
插入排序核心特性与复杂度分析
| 特性 | 指标说明 | 原理解释 |
| 时间复杂度(平均/最坏) | O(n²) | 嵌套循环比较移位,完全逆序需 n(n-1)/2 次比较与移动 |
| 时间复杂度(最好) | O(n) | 输入已有序时内层循环立即退出,仅需 n - 1 次比较 |
| 空间复杂度 | O(1) | 原地排序,仅需 current_value、j 等常数个临时变量 |
| 稳定性 | 稳定 | 仅在 arr[j] > current_value 严格成立时后移,相等键不越位 |
| 适用场景 | 小规模、基本有序或高阶排序子过程 | 逻辑紧凑且常数开销极低,小区间常快于复杂 O(n log n) 算法 |
实测移位与交换版插入排序、[7,6,9,3,1] 逐步轨迹、最好/最坏计数公式与混合归并子过程
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
一次相邻交换需要 3 次数组读写赋值,而先取出 `current_value` 后每次仅执行 1 次 `arr[j+1] = arr[j]`,最终一次性落位,约可将元素赋值次数减少至原来的三分之一。