面试前必看——堆排序、堆插入、堆删除
程序员文章站
2024-02-14 11:51:46
...
目录
1.对一个数组建最大堆,得到堆顶最大值:
def sink(self, nums, root):
if 2 * root + 1 < len(nums):
k = 2 * root + 2 if 2 * root + 2 < len(nums) and nums[2 * root + 2] > nums[2 * root + 1] else 2 * root + 1
if nums[root] < nums[k]:
(nums[root], nums[k]) = (nums[k], nums[root])
self.sink(nums, k)
for i in range(len(nums) // 2 - 1, -1, -1):
self.sink(nums, i)
print nums[0]
2.对一个数组建最大堆,得到排好序(从小到大)的数组:
class Solution:
def sink(self,s,root):
if 2*root+1<len(s):
k = 2*root+2 if 2*root+2<len(s) and s[2*root+2]>s[2*root+1] else 2*root+1
if s[k] > s[root]:
s[k],s[root] = s[root],s[k]
self.sink(s,k)
def maxheap(self,s):
for i in range(len(s)//2-1,-1,-1):#一定得从下往上来
self.sink(s,i)
return s
def heap_sort(self,s):
last = len(s)-1
self.maxheap(s)#构造最大堆
while last >0:
s[0],s[last] = s[last],s[0]
s[:last] = self.maxheap(s[:last])#因对s的切片进行最大堆排序,一定要把排序结果赋值给s,不然就没有任何结果
last -= 1
return s
answer = Solution()
print(answer.maxheap([1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]))
print(answer.heap_sort([1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]))