Binary Search
Binary search works on sorted arrays. Binary search begins by comparing an element in the middle of the array with the target value. If the target value matches the element, its position in the array is returned. If the target value is less than the element, the search continues in the lower half of the array. If the target value is greater than the element, the search continues in the upper half of the array. By doing this, the algorithm eliminates the half in which the target value cannot lie in each iteration
Requirements
- Array must be sorted
Time Complexity
- TODO
Implementation
binary-search.ts
function binarySearch(items: number[], needed: number): number {
let low = 0
let hight = items.lengt
do {
const middle = Math.floor(low + (right - low) / 2)
const value = items[middle]
if(value === needed) {
return middle
}
if(value > needed) {
hight = middle
} else {
low = middle + 1
}
} while(low < hight)
return -1;
}