Homework-1/qselect.py

16 lines
361 B
Python
Raw Normal View History

2019-09-26 23:30:53 -07:00
import random
def qselect(i, xs):
if xs == []: return None
pivot = xs.pop(random.randrange(len(xs)))
left = [x for x in xs if x < pivot]
right = [x for x in xs if x >= pivot]
2019-09-27 14:35:28 -07:00
if i > len(left) + 1:
2019-09-26 23:30:53 -07:00
return qselect(i - len(left) - 1, right)
2019-09-27 14:35:28 -07:00
elif i == len(left) + 1:
2019-09-26 23:30:53 -07:00
return pivot
else:
return qselect(i, left)