Destreation
Destreation

Reputation: 115

Identifying Exception in thread "main" java.lang.StackOverflowError

My code is below, I am trying to recursively call my binary search function but keep getting this Exception. I am trying to identify the source of the issue. Keep in mind i've excluded my code for creating the array list for simplicity and because i know they are functional.

  import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.math.*;
public class nickclass {

public static void main(String[] args) {

for(int i = 0; i <(int)listTest.size();i++)
   {
  binarySearchHelp(listTest2,(String)listTest.get(i),0,listTest2.size());
 }

void binarySearchHelp(ArrayList list, String value, int left, int right) {

    if (left > right)
        System.exit(0);

    int middle = (int) Math.floor(list.size()/2);

    if (((String) list.get(middle)).compareTo(value) == 0)
        System.out.println(list.get(middle));


    else if (((String) list.get(middle)).compareTo(value) > 0)
         binarySearchHelp(list, value, left, middle - 1);

    else
         binarySearchHelp(list, value, middle + 1, right);           

  }
}
}

Upvotes: 0

Views: 344

Answers (1)

user85421
user85421

Reputation: 29730

The recursive call is never terminating (only when all memory is used) because middle is always the middle of the list, but it should be the middle between left and right:

middle = (left + right) / 2;

I would also check that the interval (left-right) is big enough to be divided or if the algorithm can stop... and System.exit is kind of brutal, you really want to stop the virtual machine without any message?

Upvotes: 1

Related Questions