Binary Search

Intro

Binary Search finds a target in a sorted array by repeatedly cutting the search range in half. This gives logarithmic time complexity and predictable performance for large inputs. Use it when the data is sorted and random access is cheap. Example: finding a user id in a sorted list of millions of numeric ids.

Deeper Explanation

Example

public static int BinarySearch(int[] arr, int target)
{
    int left = 0;
    int right = arr.Length - 1;

    while (left <= right)
    {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target)
        {
            return mid;
        }

        if (arr[mid] < target)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }

    return -1;
}

Diagram

flowchart TD
  A[Start with sorted array and target] --> B[Set left and right]
  B --> C{left less or equal right}
  C -->|No| Z[Not found]
  C -->|Yes| D[Compute mid safely]
  D --> E{value at mid equals target}
  E -->|Yes| F[Return mid]
  E -->|No| G{value at mid less than target}
  G -->|Yes| H[Move left to mid plus one]
  G -->|No| I[Move right to mid minus one]
  H --> C
  I --> C

Pitfalls

Tradeoffs

Questions


Whats next