select i th smallest element from array

Posted by davit-datuashvili on Stack Overflow See other posts from Stack Overflow or by davit-datuashvili
Published on 2010-05-20T15:45:12Z Indexed on 2010/05/20 15:50 UTC
Read the original article Hit count: 182

Filed under:
|

i have divide and conqurer method to find i th smalles element from array here is code

public class rand_select{
     public static int  Rand_partition( int a[],int p,int q,int  i){
         //smallest in a[p..q]
 if ( p==q) return a[p];
 int r=partition (a,p,q);
 int k=r-p+1;
if (i==k) return a[r];
if (i<k){
 return Rand_partition(a,p,r-1,i);
}

  return Rand_partition(a,r-1,q,i-k);
}

public static void main(String[]args){

 int a[]=new int []{6,10,13,15,8,3,2,12};
System.out.println(Rand_partition(a,0,a.length-1,7));
}

public static  int partition(int a[],int p,int q){

 int  m=a[0];


while ( p<q){


 while (p<q && a[p++] <m){
   p++;
}
while (q>p && a[q--]>m){
 q--;
}
  int t=a[p];
a[p]=a[q];
a[q]=t;
}
 int k=0;
 for (int i=0;i<a.length;i++){
 if ( a[i]==m){
   k=i;
}

}

   return k;
}

}

but here is problem java.lang.ArrayIndexOutOfBoundsException please help me

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about java