I have a divide and conquer method to find the i th smallest element from an array. Here is the 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;
}
}
However, I get an exception when run: java.lang.ArrayIndexOutOfBoundsException.
I was able to fix a few bugs. A minor one is this line:
Instead, you want this:
That’s because you have partitioned
a[p..q]into three parts as follows:Your original code handles the
a[r]anda[p..r-1]case fine, but messes up on thea[r+1..q]by usingr-1instead.I was also able to correct and simplify
partition:Your original code had extraneous
p++andq--. Also, the search for where the pivot is is unnecessary. It’s wherepandqmeet.On naming conventions
Please follow Java naming conventions:
Related questions
On array declarations
Also, do not make a habit of declaring arrays like this:
You should instead put the brackets with the type, rather than with the identifier:
Related questions
Object[] xandObject x[]?int[] myArrayandint myArray[]in Javaint[] k,iandint k[],ii!