-
Notifications
You must be signed in to change notification settings - Fork 19
/
heap_sort.py
79 lines (57 loc) · 1.45 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
def left(i):
return 2 * i
def right(i):
return 2 * i + 1
def parent(i):
return i // 2
def is_max_heap(heap):
heap_size = len(heap) - 1
for i in range(heap_size, 1, -1):
p = parent(i)
if heap[p] < heap[i]:
return False
return True
def max_heapify(heap, heap_size, i):
l = left(i)
r = right(i)
if l <= heap_size and heap[l] > heap[i]:
largest = l
else:
largest = i
if r <= heap_size and heap[r] > heap[largest]:
largest = r
if largest != i:
heap[i], heap[largest] = heap[largest], heap[i]
max_heapify(heap, heap_size, largest)
def build_max_heap(heap):
heap_size = len(heap) - 1
for i in range(heap_size//2, 0, -1):
max_heapify(heap, heap_size, i)
def heap_sort(heap):
build_max_heap(heap)
heap_size = len(heap) - 1
for i in range(len(heap)-1, 1, -1):
heap[1], heap[i] = heap[i], heap[1]
heap_size -= 1
max_heapify(heap, heap_size, 1)
def get_maximum(heap, heap_size):
return heap[1]
def extract_max(heap, heap_size):
max_item = heap[1]
heap[1] = heap[heap_size]
heap_size -= 1
max_heapify(heap, heap_size, 1)
return max_item
def insert_node(heap, heap_size, node):
heap_size += 1
heap[heap_size] = node
i = heap_size
while i > 1 and heap[parent(i)] < heap[i]:
heap[parent(i)], heap[i] = heap[i], heap[parent(i)]
i = parent(i)
return heap_size
if __name__ == "__main__":
heap = [None, 12, 7, 1, 3, 10, 17, 19, 2, 5]
print("Before sorting:", heap)
heap_sort(heap)
print("After sorting:", heap)