Answer
Binary Search in Java
Java
public class BinarySearch {
public static void main(String[] args) {
int c, first, last, middle, n, search_element;
int array[] = { 100, 200, 300, 400, 500 };
search_element = 200;
n = array.length;
first = 0;
last = n - 1;
middle = (first + last) / 2;
while (first <= last) {
if (array[middle] < search_element)
first = middle + 1;
else if (array[middle] == search_element) {
System.out.println(search_element + " found at location " + (middle + 1) + ".");
break;
} else
last = middle - 1;
middle = (first + last) / 2;
}
if (first > last)
System.out.println(search_element + " isn't present in the list.\n");
}
}
Output
CODE
200 found at location 2.
How Binary Search Works
CODE
Array: [100, 200, 300, 400, 500] search: 200
Iteration 1:
first=0, last=4, middle=2 → array[2]=300
300 > 200 → search left: last = middle-1 = 1
Iteration 2:
first=0, last=1, middle=0 → array[0]=100
100 < 200 → search right: first = middle+1 = 1
Iteration 3:
first=1, last=1, middle=1 → array[1]=200
200 == 200 → FOUND at index 1 (location 2)
Prerequisite
Array must be sorted before binary search. Use Arrays.sort(array) if not.
Time Complexity
| Binary Search | Linear Search | |
|---|---|---|
| Best | O(1) | O(1) |
| Average | O(log n) | O(n) |
| Worst | O(log n) | O(n) |
