使用Python实现最小堆

2024-10-02 08:18:26 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我为对整数列表项执行堆排序而编写的代码。 然而,最终结果并没有达到预期的效果,因为它需要按最小顺序对列表进行排序

另外,有人可以帮助解释这个特殊代码的复杂性吗

class Heap:
    def __init__(self):
        self.heap=[]

    def insert(self,num):
        self.heap.append(num)

    def printHeap(self):
        print(self.heap)


    def heapify(self, index):

        size=len(self.heap)-1

        left=2*index+1   #calculating Left Node
        right=2*index+2  #Calculating Right Node
        minE=index

        """ Calculating the Minimum element Value from the List """
        if left <= size and self.heap[left] < self.heap[index]:
            minE=left

        if right <= size and self.heap[right] < self.heap[minE]:
            minE=right

        if minE != index:  # Swapping elelments only when MinE is not equal to the Parent Node
            self.swap(minE, index)
            self.heapify(minE)

    """ Method to Swap the elements of the Heap List  """

    def swap(self,first, second):
        self.heap[first],self.heap[second] = self.heap[second], self.heap[first]


    def minHeap(self): # Main calling Method to perform Heap

        loc=len(self.heap)-1 

        i=0
        while i <= loc:  #Running the Loop till the last element
            self.heapify(i)
            i+=1

heapList=Heap()

heapList.insert(10)
heapList.insert(15)

heapList.insert(5)
heapList.insert(2)
heapList.insert(18)
heapList.insert(3)

print(" Original List")
heapList.printHeap()

print(" Performing Heap sort:")
heapList.minHeap()

print("Final Result: ")
heapList.printHeap()

我从上述代码中得到的结果是:

Original List
[10, 15, 5, 2, 18, 3]
 Performing Heap sort:
****Final Result:
[5, 2, 3, 15, 18, 10]

然而,预期的结果是:

[2,5,3,15,18,10]

非常感谢您的宝贵意见。 谢谢


Tags: the代码selfrightindexdefleftlist

热门问题