I've been given the following pseudo-code for the quickSelect algorithm. Im a little confused about a few things, when I call the quickSelect method what am I sending in for 'k'. Also, because I need to declare count = 0 at the beginning of the method, it will always get set back to 0 in the recursive call of quickSelect which is not what I need to happen Thanks for the help, i've included the Pseudo-code as well as my code below;
Function quickSelect(aList, k):
If aList is not empty:
pivot <- Choose the element at position (len(alist)//2)
smallerList <- All elements of aList smaller than pivot
largerList <- All elements of aList larger than pivot
count <- the number of occurences of pivot value in aList
m <- the size of smallerList
if k >= m and k < m + count then:
return pivot
if m > k:
return quickSelect(smallerList,k)
else:
return quickSelect(largerlist, k-m-count)
This is what i've come up with:
def quickSelect(aList, k):
pivot = aList[len(aList)//2]
smallerList = aList[:pivot]
largerList = aList[pivot:]
m = len(smallerList)
count = 0
for i in aList:
if i == pivot:
count = count + 1
if k >= m and k < m + count:
return pivot
if m > k:
return quickSelect(smallerList, k)
else:
return quickSelect(largerList, k-m-count)