I’m very new to binary search and I attempted a code that would read values from a document and then the user can input a number to search for from the document, and through binary search, the number would be found. I’m having trouble now because the “low” variable that I initialize in the binary search section of my code is not being returned to my main code and there’s an error that says “low can not be resolved to a variable”.
Here is the code for my binary search:
static public int search (int[]numbers,int target, int count) { int high = numbers.length; int low = -1; int middle = (high+low)/2; while(high-low>1) { count++; middle = (high+low)/2; if(numbers[middle]>target) { high = middle; } else if(numbers[middle]<target) { low = middle; } else { break; } System.out.println(numbers[middle]); System.out.println(middle); } if(low == -1 || numbers[low]!=target) { low=-1; return low; } else { return low; } }
And here is the code from my main code. The part with the if statements is where the error is showing up:
public static void main(String[] args) throws IOException { DataInputStream input = new DataInputStream(System.in); int [] numbers = new int [50000]; int target; int count=0; try { BufferedReader br = new BufferedReader(new FileReader("randNums.txt")); for(int i=0;i<50000;i++) { numbers[i]=Integer.parseInt(br.readLine()); } br.close(); Arrays.sort(numbers); System.out.print("Choose a number between 1-100000000 to search for: "); target = Integer.parseInt(input.readLine()); search(numbers, target,count); if(low==-1) { System.out.println("The number was not on the list."); } else { System.out.println("The number is at position " + low); System.out.println("It took " + count + " comparisons to find the number."); } }
Answer
You have to initialize low
in main: int low=search(numbers, target,count);