[Python] python实现的堆排序算法代码 →→→→→进入此内容的聊天室

来自 , 2019-10-08, 写在 Python, 查看 130 次.
URL http://www.code666.cn/view/29c4a0e4
  1. def heapSort(a):  
  2.     def sift(start, count):  
  3.         root = start  
  4.  
  5.         while root * 2 + 1 < count:  
  6.             child = root * 2 + 1  
  7.             if child < count - 1 and a[child] < a[child + 1]:  
  8.                 child += 1  
  9.             if a[root] < a[child]:  
  10.                 a[root], a[child] = a[child], a[root]  
  11.                 root = child  
  12.             else:  
  13.                 return  
  14.  
  15.     count = len(a)  
  16.     start = count / 2 - 1  
  17.     end = count - 1  
  18.  
  19.     while start >= 0:  
  20.         sift(start, count)  
  21.         start -= 1  
  22.  
  23.     while end > 0:  
  24.         a[end], a[0] = a[0], a[end]  
  25.         sift(0, end)  
  26.         end -= 1  
  27.  
  28. a = [-8,0,1,3,11,35,68]  
  29. heapSort(a)  
  30. print a # [-8, 0, 1, 3, 11, 35, 68]
  31.  
  32.  
  33.  
  34. #//python/4603

回复 "python实现的堆排序算法代码"

这儿你可以回复上面这条便签

captcha