Skip to content

Commit 08712e7

Browse files
Add this linear time selection algorithm
This is selection algorithm which finds kth smallest/largest element in a array with linear time complexity.
1 parent 36a813e commit 08712e7

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#----Median Of Median finding algorithm implimentation in python----
2+
3+
4+
#used to avoid overflow
5+
INT_MAX=2**32
6+
7+
#finding the kth element from the list
8+
def kthS(a,k) :
9+
a.sort()
10+
return a[k-1]
11+
12+
#finding median from the fixed length of array( median of arr[] from index l to l+n )
13+
def findmedian(a,l,n):
14+
a=a[l:l+n]
15+
a.sort()
16+
return a[n//2]
17+
18+
#This funrions uses median of median algo to find kthsmallest number in linear time
19+
def kthSmallest(a,l,r,k):
20+
if k>0 and k<=r-l+1:
21+
n=r-l+1
22+
median=[0]*((n+4)//5)
23+
i=0
24+
#divide the array into smaller array of size 5 and find median of each small array
25+
while(i<n//5):
26+
median[i]=findmedian(a,l+i*5,5)
27+
i+=1
28+
# For last group with less than 5 elements
29+
if i*5<n:
30+
median[i] = findmedian(a,l+i*5, n%5)
31+
i+=1
32+
# Find median of all medians using recursive call.
33+
# If median[] has only one element, then no need
34+
# of recursive call
35+
if(i == 1):
36+
medOfMed = median[i-1]
37+
else:
38+
kthSmallest(median, 0, i-1, i//2)
39+
# Partition the array around a medOfMed
40+
# element and get position of pivot
41+
# element in sorted array
42+
pos = partition(a, l, r, medOfMed)
43+
if pos-l == k-1:
44+
return a[pos]
45+
if (pos-l > k-1):
46+
return kthSmallest(a, l, pos-1, k)
47+
return kthSmallest(a, pos+1, r, k-pos+l-1)
48+
return INT_MAX
49+
#for swapping two array elements
50+
def swap(arr, a, b):
51+
temp = arr[a]
52+
arr[a] = arr[b]
53+
arr[b] = temp
54+
55+
# It searches for x in arr[l..r],
56+
# and partitions the array around x
57+
def partition(a,l,r,x):
58+
for i in range(l,r):
59+
if (a[i] == x):
60+
break
61+
swap(a,i,r)
62+
i = l
63+
for j in range(l,r):
64+
if (a[j] <= x):
65+
swap(a,i,j)
66+
i+=1
67+
swap(a,i,r);
68+
return i;
69+
#driver code
70+
def main():
71+
#Total number of elements in the list is n
72+
n=int(input("Enter value of n:"))
73+
k=(n+1)//2
74+
a=[]
75+
#entering n elements to the lsit
76+
for i in range(n):
77+
x=int(input())
78+
a.append(x)
79+
#if total number of elements is even just print the kth elements
80+
if(n%2==0):
81+
print("result is: %d"%kthS(a,k))
82+
return
83+
#if total number of elements is odd the use median of median algo to find kth smallest
84+
print("result %d"%kthSmallest(a, 0, n-1, k))
85+
#Calling the main funtion
86+
if __name__ == '__main__':
87+
main()

0 commit comments

Comments
 (0)