Searching

Algorithms that find an element in a data structure.

Back to Algorithms
searching
medium

What is Binary Search and what is its time complexity?

Click to flip

Binary Search is an efficient algorithm for finding an element in a sorted array. It works by repeatedly dividing the search interval in half. Time Complexity: O(log n)

function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;
  
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  
  return -1; // Not found
}
Click to flip back
searchingbinary-searchtime-complexity
1 of 1