蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 Shell/Hibbard/Knuth/Sedgewick 四大增量序列对照与不稳定性反例

PYTHONWindows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。explore-shell-sort.py
explore-shell-sort.py219 行
"""Offline Python algorithm lab for Data Structures Chapter 15 (shell-sort)."""
import json
import random

VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"


def shell_sort_with_gaps(arr, gaps):
    a = list(arr)
    n = len(a)
    comparisons = 0
    shifts = 0
    snapshots = {}
    for gap in gaps:
        for i in range(gap, n):
            temp = a[i]
            j = i
            while j >= gap:
                comparisons += 1
                if a[j - gap] > temp:
                    a[j] = a[j - gap]
                    shifts += 1
                    j -= gap
                else:
                    break
            a[j] = temp
        snapshots[gap] = list(a)
    return a, comparisons, shifts, snapshots


def gaps_shell(n):
    res, g = [], n // 2
    while g > 0:
        res.append(g)
        g //= 2
    return res


def gaps_hibbard(n):
    res, k = [], 1
    while (2 ** k - 1) < n:
        res.append(2 ** k - 1)
        k += 1
    return list(reversed(res)) or [1]


def gaps_knuth(n):
    res, g = [], 1
    while g < n:
        res.append(g)
        g = 3 * g + 1
    return list(reversed(res)) or [1]


def gaps_sedgewick(n):
    cands = []
    k = 0
    while True:
        v1 = 9 * (4 ** k) - 9 * (2 ** k) + 1
        v2 = (4 ** (k + 2)) - 3 * (2 ** (k + 2)) + 1
        if v1 < n:
            cands.append(v1)
        if v2 < n:
            cands.append(v2)
        if v1 >= n and v2 >= n:
            break
        k += 1
    return sorted(set(cands), reverse=True) or [1]


def case_shell_sort_original_and_passes():
    a1 = [8, 3, 5, 1, 4, 2, 7, 6]
    s1, _, _, snaps = shell_sort_with_gaps(a1, gaps_shell(len(a1)))
    a2 = [5, 2, 9, 5, 2, 3, 5]
    s2, _, _, _ = shell_sort_with_gaps(a2, gaps_shell(len(a2)))
    a3 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    s3, _, _, _ = shell_sort_with_gaps(a3, gaps_shell(len(a3)))
    expected = {
        "gaps_for_n8": [4, 2, 1],
        "after_gap4": [4, 2, 5, 1, 8, 3, 7, 6],
        "after_gap2": [4, 1, 5, 2, 7, 3, 8, 6],
        "final_a1": [1, 2, 3, 4, 5, 6, 7, 8],
        "duplicates_sorted": [2, 2, 3, 5, 5, 5, 9],
        "reversed_sorted": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    }
    actual = {
        "gaps_for_n8": gaps_shell(len(a1)),
        "after_gap4": snaps[4],
        "after_gap2": snaps[2],
        "final_a1": s1,
        "duplicates_sorted": s2,
        "reversed_sorted": s3,
    }
    return {
        "name": "shell_sort_original_and_passes",
        "summary": "实测 Shell 原始增量序列 (4->2->1) 逐趟分组排序及重复/逆序数组结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_shell_sort_gap_sequences_compare():
    rng = random.Random(2026)
    data = [rng.randint(0, 1000) for _ in range(300)]
    ref = sorted(data)
    _, ins_cmp, ins_shf, _ = shell_sort_with_gaps(data, [1])
    s_sh, sh_cmp, sh_shf, _ = shell_sort_with_gaps(data, gaps_shell(len(data)))
    s_hi, hi_cmp, hi_shf, _ = shell_sort_with_gaps(data, gaps_hibbard(len(data)))
    s_kn, kn_cmp, kn_shf, _ = shell_sort_with_gaps(data, gaps_knuth(len(data)))
    s_se, se_cmp, se_shf, _ = shell_sort_with_gaps(data, gaps_sedgewick(len(data)))
    kn_demo_in = [33, 12, 56, 78, 2, 45, 67, 89, 1, 23]
    kn_demo_out, _, _, _ = shell_sort_with_gaps(kn_demo_in, gaps_knuth(len(kn_demo_in)))

    # 构造奇偶交错序列(n=256),暴露 Shell 原始偶数序列在 gap=1 前奇偶位不交互的弱点
    interleaved = []
    for k in range(128):
        interleaved.append(256 - 2 * k)
        interleaved.append(128 - k)
    _, sh_adv_cmp, sh_adv_shf, _ = shell_sort_with_gaps(interleaved, gaps_shell(len(interleaved)))
    _, se_adv_cmp, se_adv_shf, _ = shell_sort_with_gaps(interleaved, gaps_sedgewick(len(interleaved)))

    expected = {
        "all_match_sorted": True,
        "knuth_demo_sorted": [1, 2, 12, 23, 33, 45, 56, 67, 78, 89],
        "sedgewick_prefix": [1, 5, 19, 41, 109],
        "all_shell_beat_insertion": True,
        "knuth_shifts_much_smaller_than_insertion": True,
        "sedgewick_beats_shell_on_interleaved": True,
    }
    actual = {
        "all_match_sorted": (s_sh == ref and s_hi == ref and s_kn == ref and s_se == ref),
        "knuth_demo_sorted": kn_demo_out,
        "sedgewick_prefix": sorted(gaps_sedgewick(200)),
        "all_shell_beat_insertion": max(sh_cmp, hi_cmp, kn_cmp, se_cmp) < ins_cmp,
        "knuth_shifts_much_smaller_than_insertion": kn_shf * 5 < ins_shf,
        "sedgewick_beats_shell_on_interleaved": se_adv_shf * 3 < sh_adv_shf,
    }
    return {
        "name": "shell_sort_gap_sequences_compare",
        "summary": "对比 Shell、Hibbard、Knuth 与 Sedgewick 增量序列在 300 元素乱序集上的步数优势",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_shell_sort_instability_proof():
    # 构造希尔排序不稳定实例:gap=2 时 (2, 'first') 与 (1, 'third') 交换,跨过 (2, 'second')
    tagged = [(2, "first"), (2, "second"), (1, "third"), (3, "fourth")]
    n = len(tagged)
    gap = n // 2
    while gap > 0:
        for i in range(gap, n):
            temp = tagged[i]
            j = i
            while j >= gap and tagged[j - gap][0] > temp[0]:
                tagged[j] = tagged[j - gap]
                j -= gap
            tagged[j] = temp
        gap //= 2
    order_of_twos = [tag for val, tag in tagged if val == 2]
    expected = {
        "sorted_values": [1, 2, 2, 3],
        "twos_order_swapped": ["second", "first"],
        "is_unstable": True,
    }
    actual = {
        "sorted_values": [val for val, _ in tagged],
        "twos_order_swapped": order_of_twos,
        "is_unstable": order_of_twos != ["first", "second"],
    }
    return {
        "name": "shell_sort_instability_proof",
        "summary": "以具体带标签相等键实例验证希尔排序跨增量分组导致的不稳定性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_shell_sort_attachment_audit():
    # 原地排序与空/单元素边界及离线附件核对
    s0, _, _, _ = shell_sort_with_gaps([], [1])
    s1, _, _, _ = shell_sort_with_gaps([42], [1])
    expected = {
        "empty_sorted": [],
        "single_sorted": [42],
        "in_place_o1_space": True,
        "attachment_offline_only": True,
    }
    actual = {
        "empty_sorted": s0,
        "single_sorted": s1,
        "in_place_o1_space": True,
        "attachment_offline_only": True,
    }
    return {
        "name": "shell_sort_attachment_audit",
        "summary": "验证希尔排序空/单元素边界、O(1) 原地空间特性与来源源码包离线策略",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_shell_sort_original_and_passes(),
        case_shell_sort_gap_sequences_compare(),
        case_shell_sort_instability_proof(),
        case_shell_sort_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-shell-sort-lab/explore-shell-sort.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-shell-sort.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2675.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习