Binary Search
public class BinarySearch {
public static void main(String[] args) {
int n, low, high, middle, searchItem, search, array[];
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println("Elements in the array :");
for (int i = 0; i < 9; i++) {
System.out.print(a[i]+" ");
}
System.out.println("");
n = a.length;
Scanner in = new Scanner(System.in);
System.out.println("Enter value to find");
searchItem = in.nextInt();
low = 0;
high = n - 1;
middle = (low + high) / 2;
while (low <= high) {
if (a[middle] < searchItem) {
low = middle + 1;
} else if (a[middle] == searchItem) {
System.out.println(searchItem + " found at location " + (middle + 1) + ".");
break;
} else {
high = middle - 1;
}
middle = (low + high) / 2;
}
if (low > high) {
System.out.println(searchItem + " is not present in the list.
");
}
}
}
Output:
Elements in the array :
1 2 3 4 5 6 7 8 9
Enter value to find
6
6 found at location 6.