堆 python

83 阅读1分钟

堆中每个节点的值必须大于或者等于(或者小于等于)其子树中每个节点的值,实际上,我们还可以换一种说法,堆中每个节点的值都大于或者等于(或者小于等于)其左右子节点的值,这两种说法等价 `

class heap:
    def __init__(self, max_count: int):
        self.count = 0
        self.max_count = max_count
        self.capacity = [0] * (self.max_count + 1)

    def insert(self, num):
        if self.count >= self.max_count:
            return
        self.count += 1
        self.capacity[self.count] = num
        i = self.count
        while int(i / 2) > 0 and self.capacity[i] > self.capacity[int(i / 2)]:
            self.capacity[i], self.capacity[int(i / 2)] = self.capacity[int(i / 2)], self.capacity[i]
            i = int(i / 2)
        return
    def build_heap(self, capacity,count):
        n = len(capacity)
        mid = int(count/2)
        for i in range(mid,0, -1):
            self.heapify(capacity, count, i)


    def delete(self):
        if self.count == 0:
            return
        self.capacity[1] = self.capacity[self.count]
        self.capacity[self.count] = 0
        self.count -= 1

        self.heapify(self.capacity, self.count, 1)


    def heapify(self, a,count, i):
        pos = i
        while True:
            pos = i
            if i * 2 <= count and a[i] < a[i*2]:
                pos = i*2
            if i*2 + 1 <= count and a[pos] < a[i*2 + 1]:
                pos = i*2 + 1
            if pos == i:
                break
            a[i], a[pos] = a[pos], a[i]
            i = pos
    def heap_sort(self, nums):
        count = len(nums)
        nums = [0] + nums
        self.build_heap(nums, count)
        k = count
        print(k)
        while k > 1:
            nums[1], nums[k] = nums[k], nums[1]
            k -= 1
            count -= 1
            self.heapify(nums, k, 1)
        return nums[1:]


test_heap = heap(5)
test_heap.insert(4)
test_heap.insert(2)
test_heap.insert(1)
test_heap.insert(6)
test_heap.insert(-1)
test_heap.insert(-2)
print (test_heap.capacity)
test_heap.delete()
test_heap.delete()
print (test_heap.capacity)
print(test_heap.heap_sort([4,2,1,6,0]))

`