#!/usr/bin/env python3
from partition import partition
from random import randrange
def select(A,p,q,i):
n = q - p + 1; bad = True
if n==1: return A[p]
count = 0
while bad:
count+=1
print(f"partition trial {count}")
r = partition(A,p,q,randrange(p,q))
k = r - p
if (k == i): return A[r]
bad = (k< n//4) or (k> 3*n//4)
if (i < k):
return select(A,p,r-1,i)
else:
return select(A,r+1,q,i-k-1)
if __name__ == "__main__":
from random import choices
n=11
A = choices(range(0,100),k=n)
print("A=",A);
median = select(A,0,n-1,n//2)
print("median=",median)
B=sorted(A)
print("median via sorting = ",B[n//2])