堆的实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class MinHeap(object):

    def __init__(self):
        self.nums = []

    def _heapify_down(self, start):
        target = start  # sub

        l = 2 * start + 1
        if l < len(self.nums) and self.nums[l] < self.nums[target]:
            target = l

        r = 2 * start + 2
        if r < len(self.nums) and self.nums[r] < self.nums[target]:
            target = r

        if target != start:
            self.nums[start], self.nums[target] = self.nums[target], self.nums[start]
            self._heapify_down(start=target)

    def _heapify_up(self, start):
        target = (start - 1) // 2  # parent
        print(f'start: ({start}, {self.nums[start]}), target: ({target}, {self.nums[target] if target >= 0 else 0})')

        if target >= 0 and self.nums[target] > self.nums[start]:
            self.nums[start], self.nums[target] = self.nums[target], self.nums[start]
            print(self.nums)
            self._heapify_up(start=target)

    def push(self, num):
        self.nums.append(num)
        self._heapify_up(start=len(self.nums) - 1)

    def pop(self):
        if len(self.nums) == 1:
            return self.nums.pop()
        else:
            ret = self.nums[0]
            self.nums[0] = self.nums.pop()
            self._heapify_down(start=0)
            return ret

    def top(self):
        return self.nums[0]

复杂度分析

建堆过程复杂度 $\log(n)$,计算如下:

由于建堆过程是自底向上的,考虑一个结点数为 $n$ 的堆,有 $\frac{1}{4}n$ 的结点需要向下比较 1 次,有 $\frac{1}{8}n$ 的结点需要往下比较 2 次……设总比较次数为 $S$,堆深度 $k=\log{n}$,则有

$$ \begin{aligned} S &= n (\frac{1}{4}\cdot 1 + \frac{1}{8}\cdot 2 + \cdots + \frac{1}{2^k}\cdot (k-1)) \\ \frac{1}{2}S &= n (\frac{1}{8}\cdot 1 + \frac{1}{16}\cdot 2 + \cdots + \frac{1}{2^k}\cdot (k-2) + \frac{1}{2^{k+1}}\cdot (k-1)) \\ S - \frac{1}{2}S &= n (\frac{1}{8} + \frac{1}{16} + \cdots + \frac{1}{2^k} - \frac{1}{2^{k+1}}\cdot (k-1)) \\ \frac{1}{2}S &< \frac{1}{4}n \\ S &< 2n \end{aligned} $$

堆排序

具体见《🔢 排序算法 09. 堆排序》(本博客)。