-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7_HeapSort.py
More file actions
39 lines (36 loc) · 1.06 KB
/
7_HeapSort.py
File metadata and controls
39 lines (36 loc) · 1.06 KB
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
from SortAlgorithm import SortAlgorithm
class HeapSort(SortAlgorithm):
def __init__(self, array):
super().__init__("HeapSort", array)
def sort(self):
def upheap(n):
while n != 0:
parent = int((n - 1) / 2)
if self.compare(n, parent):
self.swap(n, parent)
n = parent
else:
break
def downheap(n):
if n == 0:
return
parent = 0
while True:
child = 2 * parent + 1
if child > n: break
if (child < n) and self.compare(child + 1, child):
child += 1
if self.compare(child, parent):
self.swap(child, parent)
parent = child
else:
break
i = 0
n = len(self.array)
while i < n:
upheap(i)
i += 1
while i > 1:
i -= 1
self.swap(0, i)
downheap(i - 1)