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;
}
- O(1)
- O(log n)
- O(n)
- O(n log n)
Difficulty: easy