1. class BinHeap:
    2. def __init__(self):
    3. self.heap_list = [0]
    4. self.current_size = 0
    5. def perc_up(self, i):
    6. while i // 2 > 0:
    7. if self.heap_list[i] < self.heap_list[i // 2]:
    8. self.heap_list[i], self.heap_list[i // 2] = self.heap_list[i // 2], self.heap_list[i]
    9. i = i // 2
    10. def insert(self, k):
    11. from ipdb import set_trace
    12. set_trace()
    13. self.heap_list.append(k)
    14. self.current_size += 1
    15. self.perc_up(self.current_size)
    16. def perc_down(self, i):
    17. while (i * 2) <= self.current_size:
    18. mc = self.min_child(i)
    19. if self.heap_list[i] > self.heap_list[mc]:
    20. self.heap_list[i], self.heap_list[mc] = self.heap_list[mc], self.heap_list[i]
    21. i = mc
    22. # 返回左右结点小的那一个
    23. def min_child(self, i):
    24. if i * 2 + 1 > self.current_size:
    25. return i * 2
    26. else:
    27. if self.heap_list[i * 2] < self.heap_list[i * 2 + 1]:
    28. return i * 2
    29. else:
    30. return i * 2 + 1
    31. def del_min(self):
    32. # The first element is 0
    33. ret_val = self.heap_list[1]
    34. self.heap_list[1] = self.heap_list[self.current_size]
    35. self.current_size = self.current_size - 1
    36. self.heap_list.pop()
    37. self.perc_down(1)
    38. return ret_val
    39. def build_heap(self, a_list):
    40. i = len(a_list) // 2
    41. self.current_size = len(a_list)
    42. self.heap_list = [0] + a_list[:]
    43. while i > 0:
    44. self.perc_down(i)
    45. i = i - 1
    46. class BinHeap():
    47. def __init__(self):
    48. self.list = []
    49. self.size = 0
    50. def upp(self, size):
    51. while size//2 > 0:
    52. if self.list[size//2-1] > self.list[size-1]:
    53. self.list[size//2-1], self.list[size-1] = self.list[size-1], self.list[size//2-1]
    54. size = size//2
    55. def insert(self, x):
    56. self.list.append(x)
    57. self.size += 1
    58. self.upp(self.size)