public class BinarySearchExample
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int element = 30;
int li = 0; // low index
int hi = arr.length - 1; // high index
boolean found = false;
while (li <= hi)
{
int mid = (li + hi) / 2;
if (arr[mid] == element)
{
System.out.println("Element found at index: " + mid);
found = true;
break;
}
if (element > arr[mid])
{
li = mid + 1; // search in right half
}
else
{
hi = mid - 1; // search in left half
}
}
if (!found)
{
System.out.println("Element not found");
}
}
}
Element found at index: 2
Case | Description | No. of Comparisons | Time Complexity |
---|---|---|---|
Worst Case | Element is not present, or found after repeatedly dividing the array until size becomes 1. | logâ‚‚n |
O(log n) |
Average Case | Element is found somewhere after a few halvings of the array. | logâ‚‚n |
Θ(log n) |
Best Case | Element is found at the first middle position checked. | 1 |
Ω(1) |
O(1)
→ only a few variables are used in iterative method; no extra memory needed.
O(log n)
→ in recursive method, due to function call stack usage.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.