@@ -70,4 +70,67 @@ public static double medianUsingCountingSort(int[] array) {
70
70
return median ;
71
71
}
72
72
73
+
74
+
75
+ // partition function similar to quick sort
76
+ // Considers last element as pivot and adds
77
+ // elements with less value to the left and
78
+ // high value to the right and also changes
79
+ // the pivot position to its respective position
80
+ // in the final array.
81
+ public static int partition (int [] arr , int low ,
82
+ int high )
83
+ {
84
+ int pivot = arr [high ], pivotloc = low ;
85
+ for (int i = low ; i <= high ; i ++) {
86
+ // inserting elements of less value
87
+ // to the left of the pivot location
88
+ if (arr [i ] < pivot ) {
89
+ int temp = arr [i ];
90
+ arr [i ] = arr [pivotloc ];
91
+ arr [pivotloc ] = temp ;
92
+ pivotloc ++;
93
+ }
94
+ }
95
+
96
+ // swapping pivot to the final pivot location
97
+ int temp = arr [high ];
98
+ arr [high ] = arr [pivotloc ];
99
+ arr [pivotloc ] = temp ;
100
+
101
+ return pivotloc ;
102
+ }
103
+
104
+ /**
105
+ * QuickSelect is a selection algorithm to find the k-th smallest element in an unordered list.
106
+ * It is related to the quick sort sorting algorithm.
107
+ */
108
+ // finds the kth position (of the sorted array)
109
+ // in a given unsorted array i.e this function
110
+ // can be used to find both kth largest and
111
+ // kth smallest element in the array.
112
+ // ASSUMPTION: all elements in arr[] are distinct
113
+ @ TimeComplexity ("O(n)" )
114
+ public static int kthSmallestWithQuickSelect (int [] arr , int low ,
115
+ int high , int k )
116
+ {
117
+ // find the partition
118
+ int partition = partition (arr , low , high );
119
+
120
+ // if partition value is equal to the kth position,
121
+ // return value at k.
122
+ if (partition == k - 1 )
123
+ return arr [partition ];
124
+
125
+ // if partition value is less than kth position,
126
+ // search right side of the array.
127
+ else if (partition < k - 1 )
128
+ return kthSmallestWithQuickSelect (arr , partition + 1 , high , k );
129
+
130
+ // if partition value is more than kth position,
131
+ // search left side of the array.
132
+ else
133
+ return kthSmallestWithQuickSelect (arr , low , partition - 1 , k );
134
+ }
135
+
73
136
}
0 commit comments