Binary Search Algorithm Explained Step by Step with Example and Code

Binary Search Algorithm Explained Step by Step with Example and Code

Binary Search is one of the most important searching algorithms in computer science. It is much faster than Linear Search and is commonly asked in coding interviews and competitive programming.

What is Binary Search?

Binary Search is an efficient algorithm used to find an element in a sorted array. It works by repeatedly dividing the search space into two halves and eliminating the half in which the element cannot be present.

Why is Binary Search Fast?

Instead of checking every element one by one, Binary Search reduces the problem size by half in every step. This makes it very fast even for large arrays.

Real Life Example

Think about searching a word in a dictionary. You don’t start from the first page. You open the middle, then decide whether to go left or right. This is exactly how Binary Search works.

Step by Step Working

Let the array be: 10, 20, 30, 40, 50, 60, 70

  • Find middle element (40)
  • If key is smaller, search left half
  • If key is larger, search right half
  • Repeat until found or range becomes empty

Binary Search Algorithm (C++)

int binarySearch(int arr[], int n, int key) {
    int low = 0, high = n - 1;
    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)
  • Average Case: O(log n)
  • Worst Case: O(log n)

Binary Search vs Linear Search

FeatureBinary SearchLinear Search
SpeedFastSlow
Array TypeSorted RequiredAny Order
Time ComplexityO(log n)O(n)

Common Interview Questions

  • Why Binary Search needs a sorted array?
  • What is the time complexity of Binary Search?
  • Implement Binary Search without recursion

Conclusion

Binary Search is a powerful and efficient algorithm. Mastering it will greatly improve your problem-solving skills and help you perform better in coding interviews.

Next Post: Sorting Algorithms – Bubble, Selection, and Insertion Sort Explained

Comments

Popular posts from this blog

Top 10 Free Coding Websites Every Beginner Should Use in 2026

Graph Data Structure – Complete Beginner to Advanced Guide with BFS, DFS and Examples

5 JavaScript Console Methods You're Not Using (But Should Be)