Binary Search Algorithm
π Data Structure and Algorithm
π 89 views
π
Nov 05, 2025
β± Estimated reading time: 1 min
Binary Search Algorithm
Binary Search is an efficient searching algorithm that works on sorted arrays by repeatedly dividing the search interval in half.
Algorithm Steps
- Sort the array (if not sorted).
- Find the middle element.
- If target equals middle element, return index.
- If target is smaller, search left half; otherwise, search right half.
Example (C++)
int binarySearch(int arr[], int low, int high, int key) {
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
Time Complexity
- Best Case: O(1)
- Worst Case: O(log n)
Advantages
- Much faster than linear search for sorted data.
Disadvantages
- Works only on sorted data.
Conclusion
Binary search is ideal for large sorted datasets due to its logarithmic time complexity.
π Some advanced sections are available for Registered Members
Register Now
Register Now
Share this Post
β Back to Tutorials