/**
* @author lautturi.com
* Java example: Binary Search in int array
*/
import java.util.*;
import java.time.*;
public class Lautturi {
public static void binarySearch(int arr[], int first, int last, int key) {
int mid ;
while (first <= last) {
mid = first+ (last - first) / 2;
if (arr[mid] < key) {
first = mid + 1;
} else if (arr[mid] == key) {
System.out.println("Element is found at index: " + mid);
break;
} else {
last = mid - 1;
}
}
if (first > last) {
System.out.println("Element is not found!");
}
}
public static void main(String[] args) {
int arr[] = { 1,12,13,21,27,36,38,43,59,106 };
int key = 38;
int last = arr.length - 1;
binarySearch(arr,0,last,key);
}
}
output:
Element is found at index: 6