python实现堆排序

def adjust_heap(res,start,end):

    '''

    调整大顶堆,其中res为待排序堆列表

    (为了便于操作res索引,res首位补0,真实数据索引从1开始)

    '''   

    i = start

    j = 2*i

    while j <= end:

        if j < end and res[j] < res[j+1]:

            j += 1

        if res[i] < res[j]:

            res[i],res[j] = res[j],res[i]

            i = j

            j = 2*i

        else:

            break

def swap(res,root,last):

    '''

    交换根节点与尾节点

    '''

    res[root],res[last] = res[last],res[root]

def sort_heap(res):

    '''

    堆排序

    '''

    res = [0] + res

    length = len(res) - 1

    last_par = length // 2  # 寻找父节点

    for i in range(last_par):

        adjust_heap(res,last_par - i,length)

    for i in range(length - 1):

        swap(res,1,length - i)

        adjust_heap(res,1,length - i - 1)

    return res[1:]

res = [50, 16, 30, 10, 60,  90,  2, 80, 70]

print(sort_heap(res))

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容