I have small python code that implements the quickselect discussed here.
import random
def Quickselect(A, k):
if not A:
return
pivot = random.choice(A)
i = 0
A1 = []
A2 = [] # Two new arrays A1, A2 to store the split lists
for i in range(len(A)):
if A[i] < pivot :
A1.append(A[i])
else:
A2.append(A[i])
if k < len(A1):
return Quickselect(A1, k)
if k > len(A) - len(A2):
return Quickselect(A2, k-(len(A) - len(A2)))
else:
return pivot
pass
def main():
A = [45,1,27,56,12,56,88]
print(Quickselect(A,2))
pass
I seem to be getting an randrange error. Is something amiss?
Edit: Implemented random.choice instead of random.randint.
The above code seems to work fine. Thanks to User Blender.
Your error occurs because
randrangebreaks when the range is empty (i.e.randrange(1, 1)).Use
random.choiceinstead and changek <= len(A1)tok < len(A1):