diff --git a/Array/Binary_Search.js b/Array/Binary_Search.js index c6e7216..d447fbe 100644 --- a/Array/Binary_Search.js +++ b/Array/Binary_Search.js @@ -5,7 +5,8 @@ let RecursiveFunction = function (arr, x, start, end) { if (start > end) return false; - let mid=Math.floor((start + end)/2); + let mid=Math.floor(start + (end - start)/2); + //rather than using mid = (start + mid)/2 using the above as in some cases (start + end) can be out of the range if (arr[mid]===x) return true; diff --git a/Search/binarySearch.js b/Search/binarySearch.js index 4280fa0..f02cd5d 100644 --- a/Search/binarySearch.js +++ b/Search/binarySearch.js @@ -2,7 +2,7 @@ function binarySearch(arr = [], key) { var left = 0, right = arr.length - 1; // left index and right index of the array while (left <= right) { - var middle = Math.floor((right + left) / 2); + var middle = Math.floor( left +(right - left) / 2); if (arr[middle] == key) return middle; else if (key > arr[middle]) { left = middle + 1;