Binary Search Problem - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Binary Search Problem

ramadan2010ramadan2010 Posts: 2Member
hello every body. I am in my senior year as a Computer Engineer, and I have (shamefully) never joined a programming forum. my friend pointed me to this forum, and I hope I can be an active member here and contribute positively to this community.

so I have an issue with a Binary Search method in Java. the method has to be static and void. I need to find the key which is n, and display a message when it is found, and the number of computations it took to find it. if i cant find it, i need to display a message that says that i didn't find it. here is my code. let me know if there is anything unclear to you. Id like to know why am i getting a StackOverFlowError Exception.

/* binary search (recursive) and output when n is found */
public static void binarySearch(int n, int[] a)
{

int low = 0;
int high = a.length- 1;
int computation = 0; /* number of computations made to find the answer*/
if(low < high)
{
int mid = (low + high - low)/2;

if( n < a[mid])
{
int[] aHalf = new int[mid];
for(int i = 0; i < aHalf.length ; i++)
{
aHalf[i] = a[i];
}
computation++;
binarySearch(n,aHalf);
}
else if( n > a[mid])
{
int[] aHalf = new int[a.length - mid];
for(int i = mid + 1; i < aHalf.length ; i++)
{
aHalf[i] = a[i];
}
computation++;
binarySearch(n,aHalf);
}
else if (n == a[mid])
{
System.out.println(" after conducting binary search. ");
System.out.println( n + " was found at i = " + mid);

}
else
{
System.out.println(" after conducting binary search. ");
System.out.println(n + " was not found in this array");
}
}

Sign In or Register to comment.