# Thread: problem with recursive binary search program

1. Member
Join Date
Jul 2007
Posts
8
Rep Power
0

## problem with recursive binary search program

Hi,
I am trying to create a recursive binary search program as follows

import java.io.*;
class SearchArray
{
int a[];
public static int binarySearch(int[] a,int ser)
{
System.out.println("Elements of the array are");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
int len = a.length;
int beg =a[0];
int end =a[len];
int mid = (beg + end)/2;
if(a[mid] > ser)
{
for(i=0;i<mid;i++)
int k[i] = a[i];
return binarySearch(k,ser); //trying to call recursively
}
else if(a[mid] < ser)
{
for(i=0;i<=mid+1;i++)
int k[i] = a[i]; //giving error
return binarySearch(k,ser); //trying to call recursively

}
else
System.out.println(mid);
}
}
class Result
{
public static void main(String args[])
{
SearchArray ob = new SearchArray();
int a[] = {1,2,4,5,8,9,10,11,13};
int b = 5;
ob.binarySearch(a,b);
}
}

DETAILS:
1)I am passing the array a and search element b from Result class.
2)returning and calling the method binarySearch within the same class.
---->The error it is showing is as follows
C:\java_programs>javac Result.java
Result.java:19: '.class' expected
int k[i] = a[i];
^
Result.java:19: not a statement
int k[i] = a[i];
^
Result.java:25: '.class' expected
int k[i] = a[i];
^
Result.java:25: not a statement
int k[i] = a[i];
^
4 errors

can anyone pls rectify this error and tell me what conceptual mistake I am doing in this program?

2. Senior Member
Join Date
Jul 2007
Posts
130
Rep Power
0
Err, sorry for asking bit stupid, but, whats a recursive binary search means?:confused:

3. Member
Join Date
Jul 2007
Posts
8
Rep Power
0
binary search is an algorithm through which we can search any element present in an array(which is sorted) by using divide and conquer approach for example
we have an array
{1,3,6,7,8,9,13,18,19}
we want to search an element 7 searching element means finding its position in the array.In binary search first we divide the array
mid = (beg+end)/2
mid will give us the mid element 8.
then we compare it with search element.
for more info on binary search refer Binary search algorithm - Wikipedia, the free encyclopedia
for my query I feel that the error is related to :
as I am storing one arry to another using for loop.

4. Member
Join Date
Aug 2007
Posts
6
Rep Power
0
You have to declare the int[] k array first - you can't declare array elements as if they were variables.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•