书p119
选择第i个最大的数,用基于快速排序的方法解决
import random
def Partitions(A
p,r):
i = p-1
x = A[r]
for j in range(p,r):
if A[j]<x:
i+=1
temp = A[i]
A[i] = A[j]
A[j] = temp
temp = A[i+1]
A[i+1] = A[r]
A[r] = temp
return i+1
def RandomizedPartition(A,p,r):
i = random.randint(p,r)
temp = A[i]
A[i] = A[r]
A[r] = temp
return Partitions(A,p,r)
def RandomizedSelect(A,p,r,i):
if p==r:
return A[p]
else:
q = RandomizedPartition(A,p,r)
k = q-p+1
if k==i:
return A[q]
elif i<k:
return RandomizedSelect(A,p,q-1,i)
else:
return RandomizedSelect(A, q+1, r, i-k)
A = [2,8,7,1,3,5,6,4,10]
print(RandomizedSelect(A,0,len(A)-1,8))