RosettaCodeData/Task/Binary-search/Java/binary-search-2.java

29 lines
850 B
Java
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
public class BinarySearchRecursive {
2013-04-10 12:38:42 -07:00
2017-09-23 10:01:46 +02:00
public static int binarySearch(int[] haystack, int needle, int lo, int hi) {
if (hi < lo) {
return -1;
2013-04-10 12:38:42 -07:00
}
int guess = (hi + lo) / 2;
2017-09-23 10:01:46 +02:00
if (haystack[guess] > needle) {
return binarySearch(haystack, needle, lo, guess - 1);
} else if (haystack[guess] < needle) {
return binarySearch(haystack, needle, guess + 1, hi);
2013-04-10 12:38:42 -07:00
}
return guess;
2017-09-23 10:01:46 +02:00
}
public static void main(String[] args) {
int[] haystack = {1, 5, 6, 7, 8, 11};
int needle = 5;
int index = binarySearch(haystack, needle, 0, haystack.length);
if (index == -1) {
System.out.println(needle + " is not in the array");
} else {
System.out.println(needle + " is at index " + index);
}
}
2013-04-10 12:38:42 -07:00
}