I'm trying to implement a binary algorithm but I really don't know how to write this program using a recursion method. Could someone help me please write this method? I have already written the easiest way for me:
import Prog1Tools.IOTools;
public class BinarySearch {
public static void showArray(int[] array) {
for(int x : array) System.out.print (x + " ");
System.out.println ();
}
public static void fillArray(int[] array, int arrayFirst) {
int i = 0;
while (i < array.length){
array[i] = arrayFirst;
i++;
arrayFirst++;
}
}
public static void main(String[] args) {
int l, p, s;
int arrayEnd = IOTools.readInt("Type a last number in the array : ");
int arrayFirst = IOTools.readInt("Type a first number in the array : ");
int[] nums = new int[arrayEnd+1-arrayFirst ];
fillArray(nums, arrayFirst);
showArray(nums);
System.out.println ("Could you please choose a number from the array above? " );
l = 0;
p = arrayEnd-arrayFirst;
loop: while (l <= p) {
s = (l + p) / 2;
String question = IOTools.readString("Is your number "+nums[s] + " or higher ?[You can answer: yes or higher] ");
switch (question){
case "yes":
System.out.println("I found a number "+nums[s]+" Your number has an index "+s +" in the array");
break loop;
case "higher":
l = s + 1;
break;
}
}
}
}
I tried such method but it doesn't work
public static int recursiveBinarySearch(int[] sortedArray, int start, int end, String question) {
if (start < end) {
int mid = start + (end - start) / 2;
if (question=="higher") {
return recursiveBinarySearch(sortedArray, start, mid, question);
} else if (question=="lower") {
return recursiveBinarySearch(sortedArray, mid+1, end , question);
} else {
return mid;
}
}
return -(start + 1);
}