I have an assignment in writing a modified quick sort. I know that the partition2 function is correct so the error must come from somewhere else (I think...).
I am getting "none" for any list I input; any help would be much appreciated!
Here is the code:
import numpy.random as rand
def randPartition(A,p,r):
randIndex = rand.randint(p,r+1)
(A[randIndex],A[r])=(A[r],A[randIndex])
return partition2(A,p,r)
def partition2(A,p,r):
x = A[r]
i1 = p-1
i2 = p-1
for j in range(p,r):
if A[j]==x:
i2+=1
(A[i2],A[j])=(A[j],A[i2])
elif A[j]<x:
i1+=1
i2+=1
(A[i1],A[j])=(A[j],A[i1])
i2+=1
(A[i2],A[r])=(A[r],A[i2])
return (i1+1,i2)
def randQuickSort2(A):
def randQuickSortRec(A,p,r):
if p<r:
q = randPartition(A,p,r)
randQuickSortRec(A,p,q[0]-1)
randQuickSortRec(A,q[1]+1,r)
randQuickSortRec(A,0,len(A)-1)
A3=[0,1,2,0,1,2,0,1,2,1]
A4=[5,6,5,5,1,3,5,2,1,7,9,5,15,100,5, 2,17,5,56]
print(randQuickSort2(A3))
print(randQuickSort2(A4))
Your code is modifying the list in-place. The methods don't return anything - that's why you get None
Try printing the list instead. Or this:
def randQuickSort2(A):
def randQuickSortRec(A,p,r):
if p<r:
q = randPartition(A,p,r)
randQuickSortRec(A,p,q[0]-1)
randQuickSortRec(A,q[1]+1,r)
return A
return randQuickSortRec(A,0,len(A)-1)