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

  1. Sort the array (if not sorted).
  2. Find the middle element.
  3. If target equals middle element, return index.
  4. 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

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes