python 實(shí)現(xiàn)堆排序算法代碼
更新時(shí)間:2012年06月05日 23:43:36 作者:
python 實(shí)現(xiàn)堆排序算法代碼,需要的朋友可以參考下
復(fù)制代碼 代碼如下:
#!/usr/bin/python
import sys
def left_child(node):
return node * 2 + 1
def right_child(node):
return node * 2 + 2
def parent(node):
if (node % 2):
return (i - 1) / 2
else:
return (i - 2) / 2
def max_heapify(array, i, heap_size):
l = left_child(i)
r = right_child(i)
largest = i
if l < heap_size and array[l] > array[i]:
largest = l
if r < heap_size and array[r] > array[largest]:
largest = r
if largest != i:
array[i], array[largest] = array[largest], array[i]
max_heapify(array, largest, heap_size)
def build_max_heap(array):
for i in range(len(array) / 2, -1, -1):
max_heapify(array, i, len(array))
def heap_sort(array):
build_max_heap(array)
for i in range(len(array) - 1, 0, -1):
array[0], array[i] = array[i], array[0]
max_heapify(array, 0, i)
if __name__ == "__main__":
array = [0, 2, 6, 98, 34, -5, 23, 11, 89, 100, 7]
heap_sort(array)
for a in array:
sys.stdout.write("%d " % a)
相關(guān)文章
python smtplib模塊實(shí)現(xiàn)發(fā)送郵件帶附件sendmail
這篇文章主要為大家詳細(xì)介紹了python smtplib模塊實(shí)現(xiàn)發(fā)送郵件帶附件sendmail,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
Python數(shù)據(jù)相關(guān)系數(shù)矩陣和熱力圖輕松實(shí)現(xiàn)教程
這篇文章主要介紹了Python數(shù)據(jù)相關(guān)系數(shù)矩陣和熱力圖輕松實(shí)現(xiàn)教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python?chinesecalendar報(bào)錯(cuò):"no?available?data?for?ye
這篇文章主要介紹了python?chinesecalendar報(bào)錯(cuò):“no?available?data?for?year?{},?only?year?between?[{},?{}]?supported“的相關(guān)知識(shí),需要的朋友可以參考下2023-03-03
pytorch查看通道數(shù) 維數(shù) 尺寸大小方式
這篇文章主要介紹了pytorch查看通道數(shù) 維數(shù) 尺寸大小方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05

