"""
Author: OhiyoX
Date: 2020-02-03
"""
def swap(tree, i, j):
temp=tree[i]
tree[i] = tree[j]
tree[j] = temp
def heapify(tree, n, i):
"""
To heapify the single heap
n indicates how many nodes, i is location
"""
if i >= n:
return
c1 = 2 * i + 1 # left node
c2 = 2 * i + 2 # right node
max = i
if c1 < n and tree[c1] > tree[i]:
max = c1
if c2 < n and tree[c2] > tree[max]:
max = c2
if max != i:
swap(tree, max, i)
def build_heap(tree, n):
"""build heap"""
last_node = n-1 # last node
parent = (last_node - 1) // 2 # last node's parent node
for i in range(parent, -1, -1):
heapify(tree, n, i)
def heap_sort(tree, n):
build_heap(tree, n)
for i in range(n-1, -1, -1):
swap(tree, i, 0)
build_heap(tree, i)
"""main"""
tree = [10, 6, 3, 2, 0, 4, 1, 7, 5, 8, 9]
n = len(tree)
heap_sort(tree, n)
show = ''
for i in range(n):
show = show + str(tree[i]) + " "
print(show)
Python 堆排序
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 最近在复习经典排序算法,自己用python也实现了一下,这里不会涉及到原理(因为网上方法已经很详细啦),就把函数贴...
- 堆排序 堆排序是利用堆这种数据结构而设计的一种排序算法,堆排序是一种选择排序,它的最坏、最好、平均时间复杂度均为O...
- ubuntu 中安装网易云音乐 安装包的下载安装包下载地址(特别注意一点,所选择的安装包) 安装过程1.按Ctrl...