工程上使用快排思想调度能力的优化算法

def insert_sort(l: list):
    for i in range(len(l)):
        for j in range(i, 0, -1):
            if l[j] < l[j - 1]:
                l[j], l[j - 1] = l[j - 1], l[j]
    return l

def quick_sort(l: list):
    length = len(l)
    if length <= 30:
        return insert_sort(l) # 数据量低于某个指标时采用插入排序,吸取算法的常数时间优越性
    p_index = random.randint(0, length - 1) # 考虑均衡数据样本数据的复杂度
    p = l[p_index]
    less = -1  # 小于n的区域
    more = length  # 大于n的区域
    index = 0  # 当前索引位置
    while index < more:
        if l[index] < p:
            less += 1  # 小于n区域右移1
            l[index], l[less] = l[less], l[index]
            index += 1  # 当前位置加1
        elif l[index] > p:
            more -= 1  # 大于n区域左移1,当前位置不变
            l[index], l[more] = l[more], l[index]
        else:
            index += 1  # 当前位置加1
    return quick_sort(l[0:less + 1]) + l[less + 1:more] + quick_sort(l[more:])

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容