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

实测三数最大值、O(1)/O(n) 空间对比、冒泡逐轮轨迹与鸡尾酒排序

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

VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"


def find_max(a, b, c):
    max_val = a if a > b else b
    if c > max_val:
        max_val = c
    return max_val


def bubble_sort_instrumented(arr):
    data = list(arr)
    n = len(data)
    comparisons = 0
    swaps = 0
    rounds = []
    for i in range(n - 1):
        swapped = False
        for j in range(0, n - 1 - i):
            comparisons += 1
            if data[j] > data[j + 1]:
                data[j], data[j + 1] = data[j + 1], data[j]
                swaps += 1
                swapped = True
        rounds.append(list(data))
        if not swapped:
            break
    return data, comparisons, swaps, rounds


def cocktail_shaker_sort(arr):
    data = list(arr)
    left, right = 0, len(data) - 1
    swapped = True
    while swapped and left < right:
        swapped = False
        for j in range(left, right):
            if data[j] > data[j + 1]:
                data[j], data[j + 1] = data[j + 1], data[j]
                swapped = True
        right -= 1
        if not swapped:
            break
        swapped = False
        for j in range(right, left, -1):
            if data[j - 1] > data[j]:
                data[j - 1], data[j] = data[j], data[j - 1]
                swapped = True
        left += 1
    return data


def case_find_max_three_numbers():
    expected = {
        "case_5_9_3": 9,
        "case_neg1_0_1": 1,
        "case_all_negative": -3,
        "case_equal": 7,
    }
    actual = {
        "case_5_9_3": find_max(5, 9, 3),
        "case_neg1_0_1": find_max(-1, 0, 1),
        "case_all_negative": find_max(-10, -3, -7),
        "case_equal": find_max(7, 7, 7),
    }
    return {
        "name": "find_max_three_numbers",
        "summary": "实测三数最大值算法实现,覆盖常规、负数与相等边界输入",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_space_complexity_comparison():
    src = [4, 15, 2, 29, 8]
    # O(1) 额外空间:仅维护单个标量 max_val
    max_val = src[0]
    for num in src:
        if num > max_val:
            max_val = num
    # O(n) 额外空间:构造等长新列表
    doubled = [num * 2 for num in src]
    expected = {
        "o1_max": 29,
        "on_doubled": [8, 30, 4, 58, 16],
        "extra_list_len_equals_n": True,
        "input_preserved": [4, 15, 2, 29, 8],
    }
    actual = {
        "o1_max": max_val,
        "on_doubled": doubled,
        "extra_list_len_equals_n": len(doubled) == len(src),
        "input_preserved": src,
    }
    return {
        "name": "space_complexity_comparison",
        "summary": "对比 O(1) 原地极值扫描与 O(n) 副本构造两种算法的空间占用特性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_bubble_sort_standard_and_trace():
    sample = [64, 34, 25, 12, 22, 11, 90]
    sorted_sample, _, _, _ = bubble_sort_instrumented(sample)
    trace_arr = [5, 3, 8, 1]
    sorted_trace, cmp_t, swp_t, rounds = bubble_sort_instrumented(trace_arr)
    expected = {
        "sorted_sample": [11, 12, 22, 25, 34, 64, 90],
        "matches_builtin": True,
        "trace_rounds": [
            [3, 5, 1, 8],
            [3, 1, 5, 8],
            [1, 3, 5, 8],
        ],
        "trace_sorted": [1, 3, 5, 8],
        "trace_comparisons": 6,
        "trace_swaps": 4,
    }
    actual = {
        "sorted_sample": sorted_sample,
        "matches_builtin": sorted_sample == sorted(sample),
        "trace_rounds": rounds,
        "trace_sorted": sorted_trace,
        "trace_comparisons": cmp_t,
        "trace_swaps": swp_t,
    }
    return {
        "name": "bubble_sort_standard_and_trace",
        "summary": "实测冒泡排序主用例及 [5, 3, 8, 1] 逐轮冒泡状态演化",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_bubble_sort_best_worst_and_cocktail():
    ordered = [1, 2, 3, 4, 5]
    reversed_arr = [5, 4, 3, 2, 1]
    _, best_cmp, best_swp, best_rounds = bubble_sort_instrumented(ordered)
    _, worst_cmp, worst_swp, _ = bubble_sort_instrumented(reversed_arr)
    cocktail_res = cocktail_shaker_sort([64, 34, 25, 12, 22, 11, 90])
    n = len(ordered)
    expected = {
        "best_comparisons_n_minus_1": n - 1,
        "best_swaps": 0,
        "best_early_exit_rounds": 1,
        "worst_comparisons_formula": n * (n - 1) // 2,
        "worst_swaps_formula": n * (n - 1) // 2,
        "cocktail_sorted": [11, 12, 22, 25, 34, 64, 90],
    }
    actual = {
        "best_comparisons_n_minus_1": best_cmp,
        "best_swaps": best_swp,
        "best_early_exit_rounds": len(best_rounds),
        "worst_comparisons_formula": worst_cmp,
        "worst_swaps_formula": worst_swp,
        "cocktail_sorted": cocktail_res,
    }
    return {
        "name": "bubble_sort_best_worst_and_cocktail",
        "summary": "验证冒泡排序最好情况 O(n) 提前退出、最坏情况 n(n-1)/2 次比较交换及双向冒泡改进",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_find_max_three_numbers(),
        case_space_complexity_comparison(),
        case_bubble_sort_standard_and_trace(),
        case_bubble_sort_best_worst_and_cocktail(),
    ]
    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-basic-algorithm-lab/explore-dsa-basic-algorithm.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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