Skip to content

Instantly share code, notes, and snippets.

@anupsavvy
Created July 26, 2011 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anupsavvy/1105979 to your computer and use it in GitHub Desktop.
Save anupsavvy/1105979 to your computer and use it in GitHub Desktop.
Write a program for finding the kth - smallest element in the array x[0..n-1] in O(n) expected time. Your algorithm may permute the elements of x.
package com.operations.search;
public class Search{
private int[] arr=null;
private int k=0;
public Search(int[] arr){
this.arr = arr;
if(this.arr == null)
throw new SearchException("Cannot accept null array");
}
/*
* Total complexity O(n)
*/
public int findKthElement(int k){
if(k < 0 || k > this.arr.length-1){
throw new SearchException("k should be less than or equal to size of the array");
}
this.k = k;
return find(0,this.arr.length-1);
}
public int find(int pivot, int high){
int kth =0;
if(pivot <= high){
int hold = 0;
int i = pivot;
for (int j = pivot+1; j <= high ; j ++){
if(this.arr[pivot] >= this.arr[j]){
hold = this.arr[i+1];
this.arr[i+1] = this.arr[j];
this.arr[j] = hold;
i++;
}
}
hold = this.arr[i];
this.arr[i] = this.arr[pivot];
this.arr[pivot] = hold;
/*
* make recursive calls
*/
if(i+1 == this.k)
return this.arr[i];
else if(this.k < i+1)
kth = find(pivot, i-1);
else
kth = find(i+1,high);
}
return kth;
}
}
class SearchException extends RuntimeException{
public SearchException(String message){
super(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment