[演算法學習]20150414.2.堆排序
阿新 • • 發佈:2019-02-04
堆排序
# -*-coding: utf-8 -*-
import string
import random
def minHeapFix(datas, i):
"""adjust datas with i as root"""
N = len(datas)
j = 2 * i + 1 # left child
while j < N:
if (j + 1 < N) and (datas[j + 1] < datas[j]): # find the min of left and right
j += 1
if datas[j] > datas[i]: # no need to swap
break
datas[i], datas[j] = datas[j], datas[i]
i = j
j = 2 * i + 1
def buildMinHeap(datas):
"""build min heap from datas"""
N = len(datas)
for i in xrange(N / 2 - 1, -1, -1):
minHeapFix(datas, i)
if __name__ == '__main__':
datas = list([random.randint(1, 100) for i in range(15)])
print datas
buildMinHeap(datas)
print datas