|
| 1 | +var array = [5, 8, 53, 56, 123, 322, 400, 2356, 8000, 23333]; |
| 2 | + |
| 3 | + |
| 4 | +/** |
| 5 | + * Recursive version of binary search. It's complexity is O(log n). |
| 6 | + * |
| 7 | + * @public |
| 8 | + */ |
| 9 | +var binarySearch = (function () { |
| 10 | + |
| 11 | + /** |
| 12 | + * Binary search. |
| 13 | + * |
| 14 | + * @pivate |
| 15 | + * @param {array} array Given array where we should find the index of the element |
| 16 | + * @param {number} key Key of the element which index should be found |
| 17 | + * @param {number} left Left index |
| 18 | + * @param {number} right Right index |
| 19 | + * @returns {number} index The index of the element or -1 if not found |
| 20 | + * |
| 21 | + */ |
| 22 | + function recursiveBinarySearch(array, key, left, right) { |
| 23 | + if (left > right) |
| 24 | + return -1; |
| 25 | + var middle = Math.floor((right + left) / 2); |
| 26 | + if (array[middle] === key) |
| 27 | + return middle; |
| 28 | + else if (array[middle] > key) |
| 29 | + return recursiveBinarySearch(array, key, left, middle - 1); |
| 30 | + else |
| 31 | + return recursiveBinarySearch(array, key, middle + 1, right); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Calls the binary search function with it's initial values. |
| 36 | + * |
| 37 | + * @param {array} array The input array |
| 38 | + * @param {number} key The key of the element which index should be found |
| 39 | + * @returns {number} index The index of the element or -1 if not found |
| 40 | + */ |
| 41 | + return function (array, key) { |
| 42 | + return recursiveBinarySearch(array, key, 0, array.length); |
| 43 | + } |
| 44 | + |
| 45 | +}()); |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +console.log(array); |
| 50 | +console.log(5, binarySearch(array, 5)); |
| 51 | +console.log(8, binarySearch(array, 8)); |
| 52 | +console.log(53, binarySearch(array, 53)); |
| 53 | +console.log(56, binarySearch(array, 56)); |
| 54 | +console.log(123, binarySearch(array, 123)); |
| 55 | +console.log(322, binarySearch(array, 322)); |
| 56 | +console.log(400, binarySearch(array, 400)); |
| 57 | +console.log(2356, binarySearch(array, 2356)); |
| 58 | +console.log(8000, binarySearch(array, 8000)); |
| 59 | +console.log(8001, binarySearch(array, 8001)); |
| 60 | +console.log(23333, binarySearch(array, 23333)); |
0 commit comments