Skip to content

Commit

Permalink
fix bug for equal items in quicksort
Browse files Browse the repository at this point in the history
  • Loading branch information
shellfly committed Jan 27, 2020
1 parent 6f78f1d commit 8b1dd0d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
22 changes: 14 additions & 8 deletions algs4/quick.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,21 @@ class Quick:
@classmethod
def partition(cls, arr, lo, hi):
v = arr[lo]
i = lo + 1
j = hi
i = lo
j = hi+1
while True:
while i < hi and arr[i] < v:
while True:
i += 1
while j > lo and arr[j] > v:
if not (i < hi and arr[i] < v):
break
while True:
j -= 1
if i >= j or i == hi or j == lo:
if not (j > lo and arr[j] > v):
break
if i >= j:
break
arr[i], arr[j] = arr[j], arr[i]

arr[lo], arr[j] = arr[j], arr[lo]
return j

Expand All @@ -59,7 +64,8 @@ def sort(cls, arr):
if __name__ == '__main__':
import sys

items = []
for line in sys.stdin:
items = line.split()
print(' items: ', items)
print('sort items: ', Quick.sort(items))
items.extend(line.split())
print(' items: ', items)
print('sort items: ', Quick.sort(items))
7 changes: 4 additions & 3 deletions algs4/quick_3way.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ def sort(cls, arr):
if __name__ == '__main__':
import sys

items = []
for line in sys.stdin:
items = line.split()
print(' items: ', items)
print('sort items: ', Quick3Way.sort(items))
items.extend(line.split())
print(' items: ', items)
print('sort items: ', Quick3Way.sort(items))

0 comments on commit 8b1dd0d

Please sign in to comment.