简体   繁体   中英

Why this recursive function is throwing StackOverFlow error???this is my logic for binary search and Where is the exact point of error in it

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);
    }           
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM