I am trying to use the quick sort algorithm to sort a random of list of any numbers, but do not know how to sort negative numbers as well, which part of the code should I work on?
Didn't know what to do, commenting out the change of code will help out a lot.
Expected Results:
>>> quickSort([3,5,-3,-1,1,2,4])
[-3, -1, 1, 2, 3, 4, 5]
Actual Results:
>>> quickSort([3,5,-3,-1,1,2,4])
[1, 2, -3, -1, 3, 4, 5]
def quickSort(numList):
n=len(numList)
if n<=1:
return numList
x, left, right = numList[0], 0, n-1
while left<right:
if numList[left]<=x:
left+=1
else:
numList[left], numList[right] = numList[right], numList[left]
right -=1
numList[0], numList[left] = numList[left], numList[0]
quickSort(numList[:left])
quickSort(numList[left+1:])
return numList
numList[:left]creates a copy ofnumListwith the specified range of elements. Same withnumList[left+1:]. Consequently, callingquicksorton them has no effect on the originalnumListthat was supplied. Thus you end up with the result of partitioning around only a single pivot (in your test case, 3). This has nothing to do with negative numbers, which a few more test cases could have easily shown.