堆排序

时间复杂度 O(nlogn) 空间复杂度(logn)

堆是用数组实现的完全二叉树

大根堆表示父节点比子节点都大,小根堆相反

堆排序的原理就是每次都将堆排序成大根堆,则头结点即为最大的数值,将头与尾交换,继续将剩余排成大根堆

heapify : 将指定节点按照大/小根堆的形式放到指定位置

def max_heapify(heap, root, len_heap):
        # 对当前节点进行处理
        p = root
        # 当节点为非叶节点才处理
        while p*2 + 1 < len_heap:
                l , r = p*2+1, p*2+2
                if r >= len_heap or heap[l] > heap[r]:
                        nex = l
                else:
                        nex = r
                
                if heap[p] < heap[nex]:
                        heap[p],heap[nex] = heap[nex],heap[p]
                        p = nex    
                else:
                        break

算法过程:

1、首先将数组排成大根堆,需要对数组中每一个元素进行heapify

def build_heap(nums):
        for i in range(len(nums)-1,-1,-1):
                max_heapify(nums, i, len(nums))

2、排序过程

def heap_sort(nums):
        build_heap(nums)
        for i in range(len(nums)-1, -1, -1):
                nums[i],nums[0] = nums[0],nums[i]
         # 因为交换了0位置,所以对0位置执行heapify max_heapify(nums,0,i)

 

posted @ 2022-09-22 13:47  Liang-ml  阅读(10)  评论(0)    收藏  举报