101 Logo
onenoughtone

Introduction to Binary Search

What is Binary Search?

Binary Search is a divide-and-conquer search algorithm that finds the position of a target value within a sorted array.

It works by repeatedly dividing the search interval in half, making it significantly faster than linear search with a time complexity of O(log n).

Key Characteristics

  • Requires Sorted Data: The array must be sorted for binary search to work correctly
  • Divide and Conquer: Repeatedly divides the search space in half
  • Logarithmic Time: O(log n) time complexity, making it very efficient for large datasets
  • Comparison-Based: Uses comparisons to determine which half to search next

How Binary Search Works

The basic steps of binary search are:

  1. Find the middle element of the array
  2. If the target value equals the middle element, return the middle index
  3. If the target value is less than the middle element, search the left half
  4. If the target value is greater than the middle element, search the right half
  5. Repeat steps 1-4 until the target is found or the search space is empty

Basic Implementation

Here's a simple implementation of binary search:

function binarySearch(arr, target) { let left = 0; let right = arr.length - 1; while (left <= right) { // Find the middle index const mid = Math.floor((left + right) / 2); // Check if target is found if (arr[mid] === target) { return mid; } // If target is less than mid, search left half if (arr[mid] > target) { right = mid - 1; } // If target is greater than mid, search right half else { left = mid + 1; } } // Target not found return -1; }

This function returns the index of the target value if found, or -1 if not found.

When to Use Binary Search

Binary search is particularly useful for:

  • Searching in Large Sorted Arrays: When you need to find an element in a large sorted dataset
  • Finding Insertion Points: Determining where to insert a new element in a sorted array
  • Optimization Problems: Finding the minimum or maximum value that satisfies a condition
  • Root Finding: Finding roots of monotonic functions
IntroVisualizePatternsPractice
101 Logo
onenoughtone