-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapSort.py
More file actions
33 lines (27 loc) · 882 Bytes
/
Copy pathheapSort.py
File metadata and controls
33 lines (27 loc) · 882 Bytes
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
def heapsort(aList):
length = len(aList) - 1
leastParent = length / 2
for i in range(leastParent, -1, -1):
moveDown(aList, i, length)
for i in range(length, 0, -1):
if aList[0] > aList[i]:
swap(aList, 0, i)
moveDown(aList, 0, i - 1)
def moveDown(aList, first, last):
largest = 2 * first + 1
while largest <= last:
# right child exists and is larger than left child
if (largest < last) and (aList[largest] < aList[largest + 1]):
largest += 1
# right child is larger than parent
if aList[largest] > aList[first]:
swap(aList, largest, first)
# move down to largest child
first = largest;
largest = 2 * first + 1
else:
return # force exit
def swap(A, x, y):
tmp = A[x]
A[x] = A[y]
A[y] = tmp