-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap_sort.py
89 lines (72 loc) · 2.84 KB
/
heap_sort.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from random import randrange
class MinHeap:
def __init__(self):
self.heap_list = [None]
self.count = 0
def parent_idx(self, idx):
return idx // 2
def left_child_idx(self, idx):
return idx * 2
def right_child_idx(self, idx):
return idx * 2 + 1
def child_present(self, idx):
return self.left_child_idx(idx) <= self.count
def retrieve_min(self):
if self.count == 0:
print("No items in heap")
return None
min = self.heap_list[1]
print("Removing: {0} from {1}".format(min, self.heap_list))
self.heap_list[1] = self.heap_list[self.count]
self.count -= 1
self.heap_list.pop()
print("Last element moved to first: {0}".format(self.heap_list))
self.heapify_down()
return min
def add(self, element):
self.count += 1
print("Adding: {0} to {1}".format(element, self.heap_list))
self.heap_list.append(element)
self.heapify_up()
def get_smaller_child_idx(self, idx):
if self.right_child_idx(idx) > self.count:
print("There is only a left child")
return self.left_child_idx(idx)
else:
left_child = self.heap_list[self.left_child_idx(idx)]
right_child = self.heap_list[self.right_child_idx(idx)]
if left_child < right_child:
print("Left child is smaller")
return self.left_child_idx(idx)
else:
print("Right child is smaller")
return self.right_child_idx(idx)
def heapify_up(self):
idx = self.count
while self.parent_idx(idx) > 0:
if self.heap_list[self.parent_idx(idx)] > self.heap_list[idx]:
tmp = self.heap_list[self.parent_idx(idx)]
print("swapping {0} with {1}".format(tmp, self.heap_list[idx]))
self.heap_list[self.parent_idx(idx)] = self.heap_list[idx]
self.heap_list[idx] = tmp
idx = self.parent_idx(idx)
print("HEAP RESTORED! {0}".format(self.heap_list))
print("")
def heapify_down(self):
idx = 1
while self.child_present(idx):
smaller_child_idx = self.get_smaller_child_idx(idx)
if self.heap_list[idx] > self.heap_list[smaller_child_idx]:
tmp = self.heap_list[smaller_child_idx]
print("swapping {0} with {1}".format(self.heap_list[idx], tmp))
self.heap_list[smaller_child_idx] = self.heap_list[idx]
self.heap_list[idx] = tmp
idx = smaller_child_idx
print("HEAP RESTORED! {0}".format(self.heap_list))
print("")
min_heap = MinHeap()
random_nums = [randrange(1, 101) for n in range(6)]
for el in random_nums:
min_heap.add(el)
while min_heap.count != 0:
min_heap.retrieve_min()