堆排序

て烟熏妆下的殇ゞ 提交于 2020-01-10 16:23:46
  1 #coding=utf-8
  2 
  3 def big_endian(arr , start , end):
  4     root = start
  5     child = root*2+1    #左孩子
  6     #print child
  7     while child <= end:
  8         if child+1 <= end and arr[child] < arr[child+1]:
  9             child += 1
 10         if arr[root] < arr[child]:
 11             arr[root],arr[child] = arr[child],arr[root]
 12             root = child
 13             child = root*2+1
 14         else:
 15             break
 16 
 17 
 18 def heap_sort(arr):
 19     first = len(arr)
 20     for start in range(first , -1 , -1):
 21         #print start
 22         big_endian(arr , start , len(arr)-1)
 23     for end in range(len(arr)-1 , 0 , -1):
 24         #print end
 25         arr[0],arr[end] = arr[end] , arr[0]
 26         big_endian(arr , 0 , end-1)
 27     return arr
 28 
 29 
 30 def main():
 31     arr = [3,1,4,9,6,7,5,8,2,10]
 32     print(heap_sort(arr))
 33 
 34 
 35 if __name__=="__main__":
 36     main()

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!