Answer the question
In order to leave comments, you need to log in
What is wrong with binary search code with recursion?
Colleagues, good afternoon!
Need help pointing out an error, what am I doing wrong?
Here is the code:
import java.util.Scanner;
class Program2 {
public static boolean recursion(int array[], int element, int left, int right) {
boolean isExist = false;
int middle = left + (right - left) / 2;
if (left <= right){
if (array[middle] < element) {
recursion(array, element, middle + 1, right);
} else if (array[middle] > element) {
recursion(array, element, left, middle - 1);
} else if (array[middle]==element) {
isExist = true;
}
}
return isExist;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberForSearch = scanner.nextInt();
int numbers[] = {1, 7, 22, 28, 31, 33, 43, 55, 87, 99};
int left = 0;
int right = numbers.length - 1;
boolean result = recursion(numbers,numberForSearch,left,right);
System.out.println(result);
}
}
Answer the question
In order to leave comments, you need to log in
You forgot to return before calling recursion - you have a method called, but its result is not used.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question