OLogN Logarithmic Time
1 min readRapid overview
O(log n) - Logarithmic Time
Operations that cut the search space in half each step.
const binarySearch = (items: number[], target: number) => {
let low = 0;
let high = items.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const value = items[mid];
if (value === target) return mid;
if (value < target) low = mid + 1;
else high = mid - 1;
}
return -1;
};
Notes
- Binary search works only on sorted data.
- Heap operations are O(log n).