I am trying to implement quicksort in python:
def partition(ls):
if len(ls) == 0:
return 0
pivot = ls[0]
i = 0
j = 1
while j < len(ls):
if ls[j] <= pivot:
i += 1
temp = ls[i]
ls[i] = ls[j]
ls[j] = temp
j += 1
ls[0] = ls[i]
ls[i] = pivot
return i
assert(partition([1,2]) == 0)
assert(partition([3,2]) == 1)
assert(partition([3,2,1,4,5]) == 2)
assert(partition([]) == 0)
assert(partition([45]) == 0)
def sort(ls):
if len(ls) == 0:
return
pivotIndex = partition(ls)
sort(ls[0:pivotIndex])
sort(ls[(pivotIndex + 1):len(ls)])
ls = [54,1,3,2,4,3,5,4]
sort(ls)
print ls
Based on my assert statements, I know that my partition algorithm works fine.
However, my sort function returns erroneous results. This snippet of code prints
[4, 1, 3, 2, 4, 3, 5, 54]
What should be the boundaries of the recursive calls to sort? I am aiming to partition the sublist to the left of the pivot and the sublist to the right of the pivot, both of which do not include the pivot itself.
The slicing copies part of the list, so in the recursive calls, you don’t modify the original list. Thus only the first
partitionmodifies the list.