import random
def randomList(count:int=10) -> list:
'''return a random list with elements from 0 to count-1'''
return random.sample(range(count), count)
# Recursively. Θ(lgn)
def maxHeapify(array, arrayLength, fatherIndex):
'''Maintain the max-heap property from the fatherIndex-th element'''
largestIndex = fatherIndex
leftIndex = 2 * fatherIndex
rightIndex = leftIndex+1
# Keep indices lower than len of the array
if leftIndex<arrayLength and array[leftIndex]>array[largestIndex]:
largestIndex = leftIndex
if rightIndex<arrayLength and array[rightIndex]>array[largestIndex]:
largestIndex = rightIndex
if largestIndex != fatherIndex:
array[largestIndex], array[fatherIndex] = array[fatherIndex], array[largestIndex]
maxHeapify(array, arrayLength, largestIndex)
# Cyclically. Θ(lgn)
def maxHeapify(array, arrayLength, fatherIndex):
'''Maintain the max-heap property from the fatherIndex-th element'''
largestIndex = fatherIndex
while True:
leftIndex = 2 * fatherIndex
rightIndex = leftIndex+1
# Keep indices lower than len of the array
if leftIndex<arrayLength and array[leftIndex]>array[largestIndex]:
largestIndex = leftIndex
if rightIndex<arrayLength and array[rightIndex]>array[largestIndex]:
largestIndex = rightIndex
if largestIndex != fatherIndex:
array[largestIndex], array[fatherIndex] = array[fatherIndex], array[largestIndex]
fatherIndex = largestIndex
else:break
# Θ(n)
def buildMaxHeap(array):
'''Convert an original array into a max heap'''
for i in reversed(range(len(array)//2)):
maxHeapify(array, len(array), i)
# Θ(nlgn)
def heapSort(array):
'''Heap sort a designated array'''
if len(array)<=1:
return
buildMaxHeap(array)
for i in reversed(range(1, len(array))):
array[0], array[i] = array[i], array[0]
maxHeapify(array, i, 0)
# Trial
array = randomList()
print(array)
heapSort(array)
print(array)
Heap Sort. Θ(nlgn)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
推薦閱讀更多精彩內(nèi)容
- 突然發(fā)現(xiàn)自己對這三種排序算法一無所知。他們是基于不比較類型的算法。在特殊情況下,時間復(fù)雜度可以達(dá)到 O(n) 看下...
- 堆排序是一種樹形選擇排序,是對直接選擇排序的有效改進(jìn)。 基本思想: 堆頂元素(即第一個元素)必為最小項(xiàng)(小頂堆)或...
- 堆排序算法,基于選擇排序的思想,利用堆結(jié)構(gòu)的性質(zhì)來完成對數(shù)據(jù)的排序。 前提準(zhǔn)備: 什么是堆結(jié)構(gòu):堆數(shù)據(jù)結(jié)構(gòu)是一種數(shù)...