二进制插入排序

"""
要运行文档测试,请执行以下命令:
python -m doctest -v binary_insertion_sort.py
或
python3 -m doctest -v binary_insertion_sort.py

要进行手动测试,请运行:
python binary_insertion_sort.py
"""

def binary_insertion_sort(collection: list) -> list:
    """
    使用二分插入排序算法对列表进行排序。

    :param collection: 包含可比较项的可变有序集合。
    :return: 相同的集合按升序排列。

    示例:
    >>> binary_insertion_sort([0, 4, 1234, 4, 1])
    [0, 1, 4, 4, 1234]
    >>> binary_insertion_sort([]) == sorted([])
    True
    >>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3])
    True
    >>> lst = ['d', 'a', 'b', 'e', 'c']
    >>> binary_insertion_sort(lst) == sorted(lst)
    True
    >>> import random
    >>> collection = random.sample(range(-50, 50), 100)
    >>> binary_insertion_sort(collection) == sorted(collection)
    True
    >>> import string
    >>> collection = random.choices(string.ascii_letters + string.digits, k=100)
    >>> binary_insertion_sort(collection) == sorted(collection)
    True
    """

    # 获取集合的长度
    n = len(collection)
    
    # 遍历集合,从索引1开始
    for i in range(1, n):
        # 获取要插入的值
        value_to_insert = collection[i]
        
        # 初始化二分查找的起始和结束位置
        low = 0
        high = i - 1

        # 二分查找
        while low <= high:
            mid = (low + high) // 2
            if value_to_insert < collection[mid]:
                high = mid - 1
            else:
                low = mid + 1
        
        # 插入值到正确的位置
        for j in range(i, low, -1):
            collection[j] = collection[j - 1]
        collection[low] = value_to_insert
    
    # 返回排序后的集合
    return collection


if __name__ == "__main__":
    # 获取用户输入,将其转换为整数列表
    user_input = input("Enter numbers separated by a comma:\n").strip()
    try:
        unsorted = [int(item) for item in user_input.split(",")]
    except ValueError:
        print("Invalid input. Please enter valid integers separated by commas.")
        raise
    
    # 打印经过二分插入排序后的结果
    print(f"{binary_insertion_sort(unsorted) = }")

 

posted @ 2024-02-01 13:54  mlhello-world  阅读(11)  评论(0编辑  收藏  举报