堆排序(建堆+排序)

最小堆 建堆和排序

PS:        以下为最小堆

                根节点为数组下标为0的元素。        父节点: i  子节点: 2*i+1  2*i+2  
建堆:插入到最后 向上堆化    给出子节点下标即可
    ①father = (son-1)//2  判断father是否比son所指元素大 是则调换
    ②将father赋值给son 重复执行① 直到 son = 0  返回

堆排序:将根节点与最后元素互换  向下堆化  给出最终父节点的最大下标t即可   父节点初始下标为 0
    ① 找到子节点中最小的值对应的下标son    son1=father*2+1 son2=father*2+2
    ② 判断father是否比son所指元素大,是则调换
    ③ 将son赋值给father 重复执行①② 直到 father > t 返回

复杂度:        时间 O(nlogn)       空间 O(1)

代码:

def conheap2(nums):
    def insertheap(son):
        if son == 0:
            return
        father = (son-1)//2
        if nums[father] > nums[son]:
            nums[father], nums[son] = nums[son], nums[father]
        insertheap(father)
    for i in range(len(nums)):
        insertheap(i)
# 堆排序
def myheapSort2(nums):
    def delheap(father, threshold):
        son1, son2 = father * 2 + 1, father * 2 + 2

        if son1 > threshold:
            return
        son = son1

        if son2 <= threshold and nums[son2] < nums[son1]:
            son = son2

        if nums[father] > nums[son]:
            nums[father], nums[son] = nums[son], nums[father]

        delheap(son, threshold)
    for i in range(len(nums)-1, 0, -1):
        nums[0], nums[i] = nums[i], nums[0]
        delheap(0, i-1)

路虽远,行则将至。事虽难,做则必成 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值