Ideas
- Starting from the middle element of the array, if the middle element happens to be the target value, the search ends.
- If the target value is greater than or less than the middle element, a binary search is performed in the half of the array that is greater or less than the middle element .
Prerequisite for binary search : the array is ordered
Time complexity : O(logN)
achieve
Existing ordered array [3, 4, 5, 6, 7, 9, 12, 15]
, binary search 12
:
Array.prototype.binarySearch = function(item) {
let low = 0;
let high = this.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const element = this[mid];
if (element > item) {
high = mid - 1;
} else if (element < item) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
};
const res = [3, 4, 5, 6, 7, 9, 12, 15].binarySearch(12);
console.log(res);
Results of the: