I am trying to find an element in an array using binary search-recursion. I am unable to figure what is wrong with the logic in the program as I am getting incorrect output. Say if I search for 5, the output I am getting is 4. Similarly I am not getting correct results for other cases as well. What might be the problem with this program ?
public class OrdArray {
private long[] a;
private int nELems;
public OrdArray(int max){
a=new long[max];
int nElems=0;
}
public int size(){
return nELems;
}
public void insert(int value){
int j;
for(j=0;j<nELems;j++){
if(a[j]>value){
break;
}
}
for(int k=nELems;k>j;k--){
a[k]=a[k-1];
}
a[j]=value;
nELems++;
}
public void display(){
for(int i=0;i<nELems;i++)
System.out.print(a[i]+" ");
System.out.println(" ");
}
public int Recursionfind(int low,int high,int key){
if(low>=high){
return nELems;
}
int mid=(low+high)/2;
if(a[mid]== key){
return mid;
}
if(a[mid]>key){
return Recursionfind(low,mid-1,key);
}
else{
return Recursionfind(mid+1,high,key);
}
}
}
class OrderedApp{
public static void main(String[] args) {
int maxsize=100;
OrdArray arr;
arr=new OrdArray(maxsize);
System.out.println("Insert array:");
arr.insert(3);
arr.insert(5);
arr.insert(1);
arr.insert(7);
arr.insert(6);
arr.insert(4);
arr.insert(8);
arr.insert(2);
arr.insert(9);
arr.display();
int n=arr.size();
System.out.println(n);
int key=5;
System.out.println("Key is :" + arr.Recursionfind(0,n-1,key));
}
}
The error lies here:
if(a[mid]== key){
return mid;
}
You match the searched value to the value of your array at place mid
. If you find it you have to return the found value not the key.
if(a[mid]== key){
return a[mid];
}
You also have to change a
from long[]
to int[]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.