Python堆排序

def heap_sink(heap, heap_size, parent_index):
    """最大堆-下沉算法"""
    child_index = 2 * parent_index + 1

    # temp保存需要下沉的父节点,用于最后赋值
    temp = heap[parent_index]

    while child_index < heap_size:
        # 如果有右孩子,且右孩子比左孩子大,则定位到右孩子
        if child_index + 1 < heap_size and heap[child_index + 1] > heap[child_index]:
            child_index += 1

        # 如果父节点的值不小于左右孩子节点的值,可直接跳出循环
        if temp >= heap[child_index]:
            break

        heap[parent_index] = heap[child_index]
        parent_index = child_index
        child_index = 2 * parent_index + 1

    heap[parent_index] = temp


def heap_sort(mylist):
    """堆排序"""
    n = len(mylist)

    # 1. 无序列表构建成最大堆
    for i in range(n - 2 // 2, -1, -1):
        heap_sink(mylist, n, i)

    # 2. 循环删除堆顶元素,移到列表尾部,调节堆产生新的堆顶
    for i in range(n - 1, 0, -1):
        mylist[0], mylist[i] = mylist[i], mylist[0]
        heap_sink(mylist, i, 0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值