Heap sort in Python

def heapsort(lst):
    n = len(lst)
    start = (n-2)/2
    for i in range(start,-1,-1):
        BiTree(lst,i,n-1)

    for i in range(n-1,0,-1):
        lst[i],lst[0]=lst[0],lst[i]
        BiTree(lst,0,i-1)
    return lst

def BiTree(lst, start, end):
  root = start
  while True:
    child = root * 2 + 1
    if child > end: break
    if child + 1 <= end and lst[child] < lst[child + 1]:
      child += 1
    if lst[root] < lst[child]:
      lst[root], lst[child] = lst[child], lst[root]
      root = child
    else:
      break


ary = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
print heapsort(ary)

 

posted @ 2017-12-08 07:43  YWU  阅读(132)  评论(0)    收藏  举报