Search algorithm applied to a sorted array by repeatedly dividing the search interval in half.
n
, binary search finds the element by repeatedly dividing the array in half.You can NOT apply binary search on an unsorted array
.
rotated array
.Side note
In each recursive call, it keeps half of the elements (remaining) and eliminates half of the elements (discarded).
Hence, the time complexity for search is:
O(log n)
Writing a binary search algorithm requires understanding of finding a middle
of the array.
// round up Math.ceil // round down Math.floor
Synonymous to "finding the median":
const evenItemsArray = [1,2,3,4,5,6,7,8]; // length = 8 // length/2 = 4 // value at length/2 = 5 // right of middle two [x, right] // value at length/2-1 = 4 // left of middle two [left, x] evenItemsArray[evenItemsArray.length/2]; // 5 evenItemsArray[evenItemsArray.length/2 - 1]; // 4 const oddItemsArray = [1,2,3,4,5,6,7]; // length = 7 // length/2 = 3.5 // floor(length/2) = 3 // value at floor(length/2) = 4 // only middle oddItemsArray[Math.floor(oddItemsArray.length/2)]; // 4