堆排序的python实现

堆排序的python实现

def max_heapify(heap, heapSize, root):
    left = 2*root+1
    right = left+1
    larger = root
    if left < heapSize and heap[larger] < heap[left]:
        larger = left
    if right < heapSize and heap[larger] < heap[right]:
        larger = right
    if larger != root:
        heap[larger], heap[root] = heap[root], heap[larger]
        max_heapify(heap, heapSize, larger)

def build_max_heap(heap):
    heap_size = len(heap)
    for i in range((heap_size - 1 - 1)//2, -1, -1):
        max_heapify(heap, heap_size, i)

def heap_sort(heap):
    build_max_heap(heap)
    for i in range(len(heap)-1, -1, -1):
        heap[0], heap[i] = heap[i], heap[0]
        max_heapify(heap, i, 0)
        

思想:首先建立最大堆,然后每次从最大堆取出最大值放到末尾,重新调整最大堆。
主要在于堆的调整,在max_heapify中实现的,每次从堆顶(已建立最大堆,只不过堆顶元素新插入)开始,向下的过程。
而最大堆的建立build_max_heap的过程是自下而上的,从第一个非叶子结点开始从下往上建立,子节点对应的父节点为(n-1)//2。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值