Binary Search algorithm implementation in Java
import java.io.Console;
public class BinarySearch {
static int[] numArr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public static void main(String args[]) {
for (int i = 0; i < numArr.length; i++) {
System.out.print(numArr[i] + "\t");
}
System.out.println("\n");
System.out.print("Search? :");
Console con = System.console();
int searchNum = Integer.parseInt(con.readLine());
int result = binarySearch(searchNum);
if (result != -1) {
System.out.println("Number found at index: " + result);
} else {
System.out.println("Number not found");
}
}
public static int binarySearch(int num) {
int lo = 0;
int high = numArr.length - 1;
int mid = -1;
while (lo <= high) {
mid = (lo + high) >>> 1;
if (numArr[mid] == num) {
return mid;
} else if (numArr[mid] < num) {
lo = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}
NOTE: Java Collections framework already uses the Binary Search algorithm implementation. you may find a reference for the same here.