python 利用list实现HeapSort(小顶堆)

本文介绍如何使用Python的list实现HeapSort(小顶堆)。虽然Python有内置模块heapq,但本文旨在学习算法和回顾数据结构。堆排序的时间复杂度为O(NlogN),实测结果验证了这一点。文章还提到了堆排序与缓存高速缓冲存储器的关系,并指出列表作为数据结构对算法效率的影响可能不大。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class minHeap(object):

    def __init__(self,list):
        self.list = list
        self.length = len(list)

    def shiftdown(self, index):
        flag=False
        while index*2 < self.length and flag==False:
            #首先处理左子树
            if self.list[index] > self.list[index*2]:
                t = index*2
            else:
                t = index
            #再看看是否存在右子树
            if index*2+1 < self.length:
                if self.list[t] > self.list[index*2+1]:
                    t = index*2+1
            if t!=index:
                self.swap(index,t)
                index=t
            else:
                flag=1

    def swap(self,child_index,parent_index):
        temp = self.list[child_index]
        self.list[child_index] = self.list[parent_index]
        self.list[parent_index] = temp

    def built_heap(self):
        index = int(len(self.list)/2)
        while index>0:
            self.shiftdown(in
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值