Reputation: 27
This is my logic for binary search and when I try to run it it gives me error of stackoverflow....I have written base condition also. Where is the exact point of error in it. For this code, I have taken global array with predefined value and given startingIndex=0 initially and lastIndex=intArray.length-1;
public static void binarySearchInteger(int searchingElement,int
startingIndex,int lastIndex) {
middleIndex=(startingIndex+lastIndex)/2;
if(searchingElement==intArray[middleIndex])
System.out.println("Found the Element");
else if(startingIndex==lastIndex&&
searchingElement!=intArray[middleIndex])
System.out.println("There is no such Element");
else {
if(intArray[middleIndex]>searchingElement)
binarySearchInteger(searchingElement,
startingIndex,middleIndex);
else
binarySearchInteger(searchingElement,middleIndex,lastIndex);
}
}
Upvotes: 0
Views: 58
Reputation: 12932
Suppose startIndex == 0
and endIndex == 1
, then middleIndex
is set to 1 / 2 == 0
(integer division). Now startIndex == middleIndex
, so your last recursive call will can the method with the exact same parameter values and cause an infinite recursion, which will lead to a stack overflow.
Since you are already comparing with the middle element, you don't need to include the middle element in the recursive searches, so replace the last recursive call with:
binarySearchInteger(searchingElement,middleIndex + 1,lastIndex);
There might be more errors in your code, but this one I found by only looking at it. You can find errors yourself by using a debugger and stepping through your code, looking exactly at what happens.
Upvotes: 1