原理:堆分为最大堆和最小堆。采用数组存放,其左右子树分别是I2,I2+1,不断调整父节点比左右子节点最大(小)关系,直至到数组末尾。每次调整完整个数组,则数组index=1的值为最大(小),将其与数组最后一位swap。然后重新调整除最后一位的剩余的数使之成为最大(小)堆,然后再次和倒数第二位交换,依次进行。
python 代码:
# -*- coding: utf-8 -*-
from random import randint
#generate a unsorted list
origin = []
def randomList():
for i in xrange(0,10,1):
origin.append(randint(-10,10))
#最大连续子序列的和
print origin
return origin
#without the recursion
def head_adjust_while(origin, i, size):
maxIndex = i
while maxIndex * 2 < size:
left = maxIndex * 2
right = maxIndex * 2 + 1
oldMaxIndex = maxIndex
if origin[left] > origin[maxIndex]:
maxIndex = left
if right < size and origin[right] > origin[maxIndex]:
maxIndex = right
if maxIndex != oldMaxIndex:
origin[maxIndex] = origin[maxIndex] + origin[oldMaxIndex]
origin[oldMaxIndex] = origin[maxIndex] - origin[oldMaxIndex]
origin[maxIndex] = origin[maxIndex] - origin[oldMaxIndex]
else:
break
def head_adjust_recursion(origin, i, size):
maxIndex = i
leftIndex = 2*i
rightIndex = 2*i + 1
if leftIndex < size and origin[leftIndex] > origin[maxIndex]:
maxIndex = leftIndex
if rightIndex < size and origin[rightIndex] > origin[maxIndex]:
maxIndex = rightIndex
if maxIndex != i:
origin[i] = origin[maxIndex] + origin[i]
origin[maxIndex] = origin[i] - origin[maxIndex]
origin[i] = origin[i] - origin[maxIndex]
head_adjust_recursion(origin, maxIndex, size)
def build_heap(origin):
size = len(origin)
for i in xrange(size/2,0,-1):
# head_adjust_recursion(origin,i,size)
head_adjust_while(origin, i, size)
def heap_sortion():
origin = randomList()
build_heap(origin)
size = len(origin)
for i in xrange(1,size-1):
origin[1] = origin[1] + origin[size-i]
origin[size-i] = origin[1] - origin[size-i]
origin[1] = origin[1] - origin[size-i]
# head_adjust_recursion(origin, 1, size-i)
head_adjust_while(origin, 1, size - i)
print origin
if __name__ == "__main__":
heap_sortion()
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。