Howdy, Stranger!

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

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.