堆排序 python

# -*- encoding:utf8 -*-
def heapsort(alist):
	# 保持最大堆
	def max_heapify(alist, idx, size):
		left = idx * 2 + 1
		right = idx * 2 + 2
		length = size
		if left < length:
			if alist[idx] > alist[left]:
				largest = idx
			else:
				largest = left

		if right < length:
			if alist[largest] < alist[right]:
				largest = right

		if left < length and idx != largest:
			alist[idx], alist[largest] = alist[largest], alist[idx]
			max_heapify(alist, largest, length)

	#建最大堆
	def build_heap(alist, length):
		for i in range((length // 2) - 1, -1, -1):
			max_heapify(alist, i, length)

	length = len(alist)
	build_heap(alist, length)
	for i in range(length - 1, 0, -1):
		alist[0], alist[i] = alist[i], alist[0]
		max_heapify(alist, 0, i)

if __name__ == '__main__':
	alist = [7,14,3,5,2,7,6,8,1,0,6,4]
	heapsort(alist)
	print alist

你可能感兴趣的:(算法,python)