1+ def partition (unsorted_array , first_index , last_index ):
2+ if first_index == last_index :
3+ return first_index
4+ else :
5+ nearest_median = median_of_medians (unsorted_array [first_index :last_index ])
6+ index_of_nearest_median = get_index_of_nearest_median (unsorted_array , first_index , last_index , nearest_median )
7+ swap (unsorted_array , first_index , index_of_nearest_median )
8+
9+ pivot = unsorted_array [first_index ]
10+ pivot_index = first_index
11+
12+ index_of_last_element = last_index
13+ less_than_pivot_index = index_of_last_element
14+ greater_than_pivot_index = first_index + 1
15+
16+ ## This while loop is used to correctly place pivot element at its correct position
17+ while 1 :
18+ while unsorted_array [greater_than_pivot_index ] < pivot and greater_than_pivot_index < last_index :
19+ greater_than_pivot_index += 1
20+ while unsorted_array [less_than_pivot_index ] > pivot and less_than_pivot_index >= first_index :
21+ less_than_pivot_index -= 1
22+
23+ if greater_than_pivot_index < less_than_pivot_index :
24+ temp = unsorted_array [greater_than_pivot_index ]
25+ unsorted_array [greater_than_pivot_index ] = unsorted_array [less_than_pivot_index ]
26+ unsorted_array [less_than_pivot_index ] = temp
27+ else :
28+ break
29+
30+ unsorted_array [pivot_index ]= unsorted_array [less_than_pivot_index ]
31+ unsorted_array [less_than_pivot_index ]= pivot
32+ return less_than_pivot_index
33+
34+ def median_of_medians (elems ):
35+ sublists = [elems [j :j + 5 ] for j in range (0 , len (elems ), 5 )]
36+ medians = []
37+ for sublist in sublists :
38+ medians .append (sorted (sublist )[int (len (sublist )/ 2 )])
39+ if len (medians ) <= 5 :
40+ return sorted (medians )[int (len (medians )/ 2 )]
41+ else :
42+ return median_of_medians (medians )
43+
44+ def get_index_of_nearest_median (array_list , first , last , median ):
45+ if first == last :
46+ return first
47+ else :
48+ return array_list .index (median )
49+
50+ def swap (array_list , first , index_of_nearest_median ):
51+ temp = array_list [first ]
52+ array_list [first ] = array_list [index_of_nearest_median ]
53+ array_list [index_of_nearest_median ] = temp
54+
55+
56+ def deterministic_selection (array_list , start , end , k ):
57+ split = partition (array_list , start , end )
58+ if split == k :
59+ return array_list [split ]
60+ elif split < k :
61+ return deterministic_selection (array_list , split + 1 , end , k )
62+ else :
63+ return deterministic_selection (array_list , start , split - 1 , k )
64+
65+
66+ #Output of deterministic selection
67+ list1 = [2 , 3 , 5 , 4 , 1 , 12 , 11 , 13 , 16 , 7 , 8 , 6 , 10 , 9 , 17 , 15 , 19 , 20 , 18 , 23 , 21 , 22 , 25 , 24 , 14 ]
68+ print ("The 6th smallest element is" , deterministic_selection (list1 , 0 , len (list1 )- 1 , 5 ))
0 commit comments