python 堆排序的两种实现
import heapq
#-*- coding: UTF-8 -*-
import numpy as np
def MakeHeap(a):
for i in range(int(a.size / 2) - 1, -1, -1):#对非叶子节点的子节点进行调节,构建堆
AdjustHeap(a, i, a.size)
def AdjustHeap(a, i, n):
j = i*2 +1 #选择节点i的左子节点
x = a[i] #选择节点的数值
while j < n: #循环对子节点及其子树进行调整
if j + 1 < n and a[j+1] < a[j]: #找到节点i子节点的最小值
j += 1
if a[j] >= x : #若两个子节点均不小于该节点,则不同调整
break
a[i], a[j] = a[j], a[i] #将节点i的数值与其子节点中最小者的数值进行对调
i = j #将i赋为改变的子节点的索引
j = i*2 + 1 #将j赋为节点对应的左子节点
def HeapSort(a):
MakeHeap(a) #构建小顶堆
for i in range(a.size - 1,0, -1): #对堆中的元素逆向遍历
a[i], a[0] = a[0], a[i] #将堆顶元素与堆中最后一个元素进行对调,因为小顶堆中堆顶元素永远最小,因此,输出即为最小元素
AdjustHeap(a, 0, i) #重新调整使剩下的元素仍为一个堆
if __name__ == '__main__':
a = np.random.randint(0, 100, size = 10)
print ("Before sorting...")
print ("---------------------------------------------------------------")
print (a)
print ("---------------------------------------------------------------")
a1=a
HeapSort(a1)
print ("After sorting...")
print ("---------------------------------------------------------------")
print (a1[::-1] ) #因为堆排序按大到小进行排列,采用a[::-1]对其按从小到大进行输出
print(a1)
print( "---------------------------------------------------------------")
b=list(a)
heapq.heapify(b)
heap = []
while b:
heap.append(heapq.heappop(b))
b[:] = heap
print ('-------------------------------------------------')
print ('sdk sorted',b)
Before sorting...
---------------------------------------------------------------
[92 97 3 60 8 67 13 65 35 94]
---------------------------------------------------------------
After sorting...
---------------------------------------------------------------
[ 3 8 13 35 60 65 67 92 94 97]
[97 94 92 67 65 60 35 13 8 3]
---------------------------------------------------------------
-------------------------------------------------
sdk sorted [3, 8, 13, 35, 60, 65, 67, 92, 94, 97]
posted on 2018-06-27 10:43 luoganttcc 阅读(...) 评论(...) 编辑 收藏