def MyPartition(a,p,r):
x = a[r]
i = p-1
for j in range(p,r):
if a[j]<=x:
i=i+1
a[i],a[j] = a[j],a[i]
a[i+1],a[r] = a[r],a[i+1]
return i+1
def MyRandomizedPartition(a,p,r):
if p>r:
print 'p must be smaller than r!'
return
import random
k = int(random.random()*(r-p+1)+p)
a[k],a[r] = a[r],a[k]
return MyPartition(a,p,r)
def MyRandomizedSelect(a,p,r,i):
if p==r:
return a[p]
q = MyRandomizedPartition(a,p,r)
k = q-p+1
if i==k:
return a[q]
elif i<k:
return MyRandomizedSelect(a,p,q-1,i)
else:
return MyRandomizedSelect(a,q+1,r,i-k)