forked from Jack-Lee-Hiter/AlgorithmsByPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapSort.py
26 lines (25 loc) · 880 Bytes
/
heapSort.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
def heapSort(alist):
if alist == None or len(alist) == 0:
return
length = len(alist)
output = []
for i in range(length):
tempLen = len(alist)
for j in range(tempLen//2-1, -1, -1):
preIndex = j
preVal, heap = alist[preIndex], False
while 2 * preIndex < tempLen - 1 and not heap:
curIndex = 2 * preIndex + 1
if curIndex < tempLen - 1:
if alist[curIndex] < alist[curIndex+1]:
curIndex += 1
if preVal >= alist[curIndex]:
heap = True
else:
alist[preIndex] = alist[curIndex]
preIndex = curIndex
alist[preIndex] = preVal
output.insert(0, alist.pop(0))
return output
test = [2, 6, 5, 9, 10, 3, 7]
print(heapSort(test))