創建最大(小)堆
二叉堆本質上是一種完全二叉樹,存儲方式並不是鏈式存儲,而是順序存儲
-
堆操作:插入(葉子節點上調),刪除(堆頂元素下沉)
-
堆創建:非葉子節點下沉(從最后一個非葉子節點開始)
-
最小堆:
最小堆任何一個父節點的值,都小於等於它左右孩子節點的值
創建過程:如果非葉子節點值大於其子節點,將其下沉
-
最大堆:
最大堆任何一個父節點的值,都大於等於它左右孩子節點的值。
創建過程:如果非葉子節點值小於其子節點,將其下沉
-
#最小堆
def upadjust(nums):
childindex = len(nums)-1
parentindex = (childindex-1)//2
temp = nums[childindex] #插入的葉子節點值
while childindex>0 and temp<nums[parentindex]:#子節點小於父節點,上調子節點
nums[childindex] = nums[parentindex]
childindex = parentindex
parentindex = (parentindex-1)//2
nums[childindex] = temp
def downadjust(nums,parentindex):
temp = nums[parentindex]
childindex = 2*parentindex + 1
while childindex < len(nums):
#右孩子值小於左孩子,父節點和小的交換
if childindex +1 <len(nums) and nums[childindex+1] < nums[childindex]:
childindex += 1
if temp < nums[childindex]: #父節點小於子節點,不用調整
break
nums[parentindex] = nums[childindex]
parentindex = childindex
childindex = childindex*2+1
nums[parentindex] = temp
def buildMinHeap(nums):
for i in range((len(nums)-1)//2,-1,-1):
downadjust(nums,i)
>>> nums = [5,8,6,3,9,2,1,7,0]
>>> buildMinHeap(nums)
>>> nums
[0, 3, 1, 5, 9, 2, 6, 7, 8]
#最大堆
#非葉子節點小值下沉
def downadjust(nums,parentindex):
temp = nums[parentindex]
childindex = 2*parentindex + 1
while childindex < len(nums):
if childindex +1 <len(nums) and nums[childindex+1] > nums[childindex]:#右孩子值大於左孩子,父節點和大的交換
childindex += 1
if temp > nums[childindex]: #父節點大於子節點,不用調整
break
nums[parentindex] = nums[childindex]
parentindex = childindex
childindex = childindex*2+1
nums[parentindex] = temp
def buildMaxHeap(nums):
for i in range((len(nums)-1)//2,-1,-1):
downadjust(nums,i)
>>> nums = [5,8,6,3,9,2,1,7,0]
>>> buildMaxHeap(nums)
>>> nums
[9, 8, 6, 7, 5, 2, 1, 3, 0]
python自帶堆模塊
>>> import heapq
#默認最小堆
>>> nums = [5,8,6,3,9,2,1,7,0]
>>> heapq.heapify(nums)
>>> nums
[0, 3, 1, 5, 9, 2, 6, 7, 8]
