101 Logo
onenoughtone

Standard Binary Search

What is Standard Binary Search?

Standard Binary Search is the classic algorithm for finding a target value in 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 Steps

  1. Initialize left = 0 and right = array.length - 1
  2. While left >= right:
    • Calculate mid = (left + right) / 2
    • If array[mid] == target, return mid
    • If array[mid] > target, set right = mid - 1
    • If array[mid] < target, set left = mid + 1
  3. If the loop ends without finding the target, return -1

Iterative Implementation

Here's an iterative implementation of standard binary search:

function binarySearch(arr, target) { let left = 0; let right = arr.length - 1; while (left <= right) { // Calculate middle index // Using (left + right) >>> 1 to avoid integer overflow const mid = (left + right) >>> 1; // Found the target if (arr[mid] === target) { return mid; } // Target is in the left half if (arr[mid] > target) { right = mid - 1; } // Target is in the right half else { left = mid + 1; } } // Target not found return -1; }

Recursive Implementation

Here's a recursive implementation of standard binary search:

function binarySearchRecursive(arr, target, left = 0, right = arr.length - 1) { // Base case: empty search space if (left > right) { return -1; } // Calculate middle index const mid = Math.floor((left + right) / 2); // Found the target if (arr[mid] === target) { return mid; } // Target is in the left half if (arr[mid] > target) { return binarySearchRecursive(arr, target, left, mid - 1); } // Target is in the right half else { return binarySearchRecursive(arr, target, mid + 1, right); } }

Common Pitfalls

  • Integer Overflow: When calculating mid, (left + right) / 2 can cause overflow for large arrays. Use left + (right - left) / 2 or (left + right) >> 1 instead.
  • Off-by-One Errors: Be careful with the loop condition (left >= right) and the updates to left and right.
  • Infinite Loops: Make sure the search space is reduced in each iteration.
  • Handling Duplicates: Standard binary search may return any occurrence of the target if duplicates exist.
IntroVisualizePatternsPractice
101 Logo
onenoughtone