quick select avg O(n), worst O(n^2)
Kth smallest element in Unsorted Array
#quickselect
import random
random.seed(5)
def partition(a):
"""
Usage: (left,pivot,right) = Partition(array)
Partitions an array around a randomly chosen pivot such that
left elements <= pivot <= right elements.
Running time: O(n)
"""
if len(a)==1:
return ([],a[0],[])
if len(a)==2:
if a[0]<=a[1]:
return ([],a[0],a[1])
else:
return ([],a[1],a[0])
#choose a random pivot
p=random.randint(0,len(a)-1)#the pivot index
pivot=a[p]
right=[]
left=[]
for i in range(len(a)):
if not i==p:
if a[i]>pivot:
right.append(a[i])
else:
left.append(a[i])
return (left,pivot,right)
def quickselect(a,k):
"""
Usage: kth_smallest_element = QuickSelect(array,k)
Finds the kth smallest element of an array in linear time.
"""
(left,pivot,right)=partition(a)
print((left,pivot,right))
if len(left)==k-1:
result=pivot
elif len(left)>k-1:
result=quickselect(left,k)
else:
result=quickselect(right,k-len(left)-1)
return result
def mainqs():
N=10
k=4
a=[random.randint(1,100) for i in range(N)]
print('input array:',a)
print('k=',k)
b=quickselect(a,k)
print('kth smallest element:',b)
mainqs()
kth largest
def partition1(a):
"""
Usage: (left,pivot,right) = Partition(array)
Partitions an array around a randomly chosen pivot such that
left elements <= pivot <= right elements.
Running time: O(n)
"""
if len(a)==1:
return ([],a[0],[])
if len(a)==2:
if a[0]>=a[1]:
return ([],a[0],a[1])
else:
return ([],a[1],a[0])
#choose a random pivot
p=random.randint(0,len(a)-1)#the pivot index
pivot=a[p]
right=[]
left=[]
for i in range(len(a)):
if not i==p:
if a[i]<=pivot:
right.append(a[i])
else:
left.append(a[i])
return (left,pivot,right)
def quickselect1(a,k):
"""
Usage: kth_smallest_element = QuickSelect(array,k)
Finds the kth smallest element of an array in linear time.
"""
(left,pivot,right)=partition1(a)
print((left,pivot,right))
if len(left)==k-1:
result=pivot
elif len(left)>k-1:
result=quickselect1(left,k)
else:
result=quickselect1(right,k-len(left)-1)
return result
def mainqs1():
N=10
k=4
a=[random.randint(1,100) for i in range(N)]
print('input array:',a)
print('k=',k)
b=quickselect1(a,k)
print('kth largest element:',b)
mainqs1()