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

30 lines
835 B
Java
Raw Normal View History

2017-09-23 10:01:46 +02:00
public class BinarySearchIterative {
public static int binarySearch(int[] nums, int check) {
2013-04-10 12:38:42 -07:00
int hi = nums.length - 1;
int lo = 0;
2017-09-23 10:01:46 +02:00
while (hi >= lo) {
int guess = lo + ((hi - lo) / 2);
if (nums[guess] > check) {
hi = guess - 1;
} else if (nums[guess] < check) {
lo = guess + 1;
} else {
return guess;
}
2013-04-10 12:38:42 -07:00
}
return -1;
2017-09-23 10:01:46 +02:00
}
2013-04-10 12:38:42 -07:00
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);
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
}