Find the Kth smallest element in an unsorted array.
Thoughts:
We can solve it by Divide and Conquer.
First, select an element as pivot and split the array into two sub-arrays, smaller (A) and greater (B) than pivot.
Then,
If the length of A is greater than k, we delegate the task to this array.
If the length of A is smaller than k, we delegate the task to array B, and to find the (k-|A|)th smallest number in B.
Otherwise, return the pivot value.
Code:
public static int kthSmall(int[]a, int k){ if(k == a.length) return a[a.length-1]; else return kthSmall(a, k, 0, a.length-1); } public static int kthSmall(int[] a, int k, int start, int end){ int j = start; int i = j-1; int pivot = a[end]; for(;j<end;j++){ if(a[j] < pivot){ i++; swap(a, i, j); } } i++; swap(a, i, end); int small = i-start+1; if(small == k){ return a[i]; }else if(small > k){ return kthSmall(a, k, start, i-1); }else{ //small is less than k return kthSmall(a, k-small, i+1, end); } } public static void swap(int[] a, int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; }
Time Complexity:
O(kN), which is effective when k is small.