堆排序

堆排序是一种选择排序。

选择排序:每趟从待排序的记录中选出关键字最小的记录,顺序放在已排序的记录序列末尾,直到全部排序结束为止。

def HeadSort(input_list):
    def HeadAdjust(input_list,parent,length):
        temp=input_list[parent]
        child=2*parent+1
        while child<length:
            if child+1<length and input_list[child]<input_list[child+1]:
                child+=1
            if temp>=input_list[child]:
                break
            input_list[parent]=input_list[child]
            parent=child
            child=2*parent+1
        input_list[parent]=temp
    if len(input_list)==0:
        return []
    sorted_list=input_list
    length=len(sorted_list)
    for i in range(0,length//2)[::-1]:
        HeadAdjust(sorted_list,i,length)
    for j in range(1,length)[::-1]:
        sorted_list[j],sorted_list[0]=sorted_list[0],sorted_list[j]
        HeadAdjust(sorted_list,0,j)
        print ("第%d趟排序:"%(length-j),end ='')
        print(sorted_list)
    return sorted_list
if __name__ == "__main__":
    input_list=[6,4,8,9,2,3,1]
    print('排序前:',input_list)
    sorted_list=HeadSort(input_list)
    print('排序后:',sorted_list)
排序前: [6, 4, 8, 9, 2, 3, 1]
第1趟排序:[8, 6, 3, 4, 2, 1, 9]
第2趟排序:[6, 4, 3, 1, 2, 8, 9]
第3趟排序:[4, 2, 3, 1, 6, 8, 9]
第4趟排序:[3, 2, 1, 4, 6, 8, 9]
第5趟排序:[2, 1, 3, 4, 6, 8, 9]
第6趟排序:[1, 2, 3, 4, 6, 8, 9]
排序前: [1, 2, 3, 4, 6, 8, 9]

(1)根据初始数组去构造初始堆(构建一个完全二叉树,保证所有的父结点都比它的孩子结点数值大)。
(2)每次交换第一个和最后一个元素,输出最后一个元素(最大值),然后把剩下元素重新调整为大根堆。
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值