Heap Sort. Θ(nlgn)

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容