Skip to content

Commit a667d82

Browse files
fix bug
1 parent eceace8 commit a667d82

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

heapSort.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,22 @@ def heapSort(alist):
55
output = []
66
for i in range(length):
77
tempLen = len(alist)
8-
for j in range((tempLen-1)//2, -1, -1):
9-
k = j
10-
v, heap = alist[k], False
11-
while not heap and 2*k <= tempLen-1:
12-
index = 2 * k
13-
if index < tempLen-1:
14-
if alist[index] < alist[index+1]:
15-
index += 1
16-
if v >= alist[index]:
8+
for j in range(tempLen//2-1, -1, -1):
9+
preIndex = j
10+
preVal, heap = alist[preIndex], False
11+
while 2 * preIndex <= tempLen - 1 and not heap:
12+
curIndex = 2 * preIndex + 1
13+
if curIndex < tempLen - 1:
14+
if alist[curIndex] < alist[curIndex+1]:
15+
curIndex += 1
16+
if preVal >= alist[curIndex]:
1717
heap = True
1818
else:
19-
alist[k] = alist[index]
20-
k = index
21-
alist[k] = v
22-
heapVal = alist.pop(0)
23-
output.insert(0, heapVal)
19+
alist[preIndex] = alist[curIndex]
20+
preIndex = curIndex
21+
alist[preIndex] = preVal
22+
output.insert(0, alist.pop(0))
2423
return output
2524

2625
test = [2, 6, 5, 9, 10, 3, 7]
27-
print(heapSort(test))
26+
print(heapSort(test))

0 commit comments

Comments
 (0)