Skip to content

Commit c4b94d1

Browse files
committed
fix index out of range
1 parent 0cbf915 commit c4b94d1

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

QuickSort.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# coding: utf-8
2+
13
def quickSort(alist):
24
quickSortHelper(alist, 0, len(alist)-1)
35

@@ -16,9 +18,9 @@ def partition(alist, first, last):
1618
done = False
1719

1820
while not done:
19-
while alist[leftmark] <= pivotvlue and leftmark <= rightmark:
21+
while leftmark <= rightmark and alist[leftmark] <= pivotvlue: # bugfix: 先比较index, 不然数组会越界
2022
leftmark += 1
21-
while alist[rightmark] >= pivotvlue and rightmark >= leftmark:
23+
while rightmark >= leftmark and alist[rightmark] >= pivotvlue:
2224
rightmark -= 1
2325

2426
if leftmark > rightmark:
@@ -32,3 +34,13 @@ def partition(alist, first, last):
3234
alist2 = [1]
3335
quickSort(alist2)
3436
print(alist2)
37+
38+
39+
if __name__ == "__main__":
40+
test_data = [3,2,111,3,-1,0,0,1,0,2,4]
41+
42+
res_stable = sorted(test_data)
43+
quickSort(test_data)
44+
print(test_data)
45+
print(res_stable)
46+
assert all(map(lambda x: x[0] == x[1], zip(res_stable, test_data)))

0 commit comments

Comments
 (0)