* Searches for specific element in a given array using * the binary search algorithm. * Time complexity: O(log N). * * @example * * var search = require('path-to-algorithms/src/searching/'+ * 'binarysearch').binarySearch; * console.log(search([1, 2, 3, 4, 5], 4)); //
(array, value, key)
| 22 | * @returns {Number} Index of the element or -1 if not found. |
| 23 | */ |
| 24 | function binarySearch(array, value, key) { |
| 25 | key = !key ? id : typeof key === 'string' ? get(key) : key; |
| 26 | value = key(value); |
| 27 | var middle = Math.floor(array.length / 2); |
| 28 | var left = 0; |
| 29 | var right = array.length; |
| 30 | while (right >= left) { |
| 31 | var middleValue = key(array[middle]); |
| 32 | if (middleValue === value) { |
| 33 | return middle; |
| 34 | } else if (middleValue > value) { |
| 35 | right = middle - 1; |
| 36 | } else { |
| 37 | left = middle + 1; |
| 38 | } |
| 39 | middle = Math.floor((left + right) / 2); |
| 40 | } |
| 41 | return -1; |
| 42 | } |
| 43 | |
| 44 | exports.binarySearch = binarySearch; |
| 45 |
no test coverage detected