python實現堆排序

#!/usr/bin/python
from sortCommon import swap
#下沉操做
def shiftDown(dataArray, i, size):
	while(int(i*2+1)<size):
		t = int(i*2+1)
		if t+1 < size and dataArray[t+1] < dataArray[t]:
			t+=1
		if dataArray[i] > dataArray[t]:
			swap(dataArray, i, t)
			i = t
		else:break
#建堆
def buildHeap(dataArray):
	#對每個非葉子節點進行下沉操做
	for i in range(int(len(dataArray)/2)-1, -1, -1):
		shiftDown(dataArray, i, len(dataArray))
def sort(dataArray):
	heapSize = len(dataArray)
	#建堆
	buildHeap(dataArray)
	while(heapSize > 1):
		#把堆頂元素與最後一個元素交換,以後從堆中去掉最後一個元素,再對堆頂元素進行下沉操做
		heapSize-=1
		swap(dataArray, 0, heapSize)
		shiftDown(dataArray, 0, heapSize)

參考連接:html

http://www.javashuo.com/article/p-wjfxplqz-z.htmlpython

http://www.javashuo.com/article/p-wfvodyqs-ep.htmlui

相關文章
相關標籤/搜索