堆排序

如何用代码表示一个堆:

如何用数组存储一个堆:
[0,1,2,3,4,5,6,7,8,9,10]
父节点:
parent = (i-1)/2
两个子节点:
c1 = 2i+1
c2 = 2i+2

'''
parent = (i-1)/2
c1 = 2i+1
c2 = 2i+2
'''
def swap(arr, i, j):
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
def heapify(tree, n, i):#调整操作
    if i >= n:
        return
    c1 = 2 * i + 1
    c2 = 2 * i + 2
    max = i
    if c1 < n and tree[c1] > tree[max]:
        max = c1
    if c2 < n and tree[c2] > tree[max]:
        max = c2
    if max != i:
        swap(tree, max, i)
        heapify(tree, n, max)
def build_heap(tree, n):#自下往上调整
    last_node = n-1
    parent = int((last_node-1)/2)
    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)
        heapify(tree, i, 0)
#tree = [4, 10, 3, 5, 1, 2]
tree = [2, 5, 3, 1, 10, 4]
n = 6
#build_heap(tree, n)
heap_sort(tree, n)
print(tree)

复杂度分析:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值