CS Fundamentals Trainer · Algorithms & Data Structures · JavaScript

What is the time complexity of this code?

function binarySearch(sorted, target) {
  let lo = 0;
  let hi = sorted.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (sorted[mid] === target) return mid;
    if (sorted[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}
  1. O(1)
  2. O(log n)
  3. O(n)
  4. O(n log n)

Difficulty: easy

Answer this question

Related questions