diff --git a/Recursive/BinarySearch.js b/Recursive/BinarySearch.js index 6f6e216df1..4c9a2d78a7 100644 --- a/Recursive/BinarySearch.js +++ b/Recursive/BinarySearch.js @@ -10,27 +10,25 @@ * @see [BinarySearch](https://en.wikipedia.org/wiki/Binary_search_algorithm) */ -const binarySearch = (arr, low = 0, high = arr.length - 1, searchValue) => { - if (high >= low) { - const mid = low + Math.floor((high - low) / 2) +const binarySearch = (arr, searchValue, low = 0, high = arr.length - 1) => { + // base case + if (high < low || arr.length === 0) return -1 - // If the element is present at the middle - if (arr[mid] === searchValue) { - return mid - } + const mid = low + Math.floor((high - low) / 2) - // If element is smaller than mid, then - // it can only be present in left subarray - if (arr[mid] > searchValue) { - return binarySearch(arr, low, mid - 1, searchValue) - } + // If the element is present at the middle + if (arr[mid] === searchValue) { + return mid + } - // Else the element can only be present in right subarray - return binarySearch(arr, mid + 1, high, searchValue) + // If element is smaller than mid, then + // it can only be present in left subarray + if (arr[mid] > searchValue) { + return binarySearch(arr, searchValue, low, mid - 1) } - // We reach here when element is not present in array - return -1 + // Else the element can only be present in right subarray + return binarySearch(arr, searchValue, mid + 1, high) } export { binarySearch } diff --git a/Recursive/test/BinarySearch.test.js b/Recursive/test/BinarySearch.test.js index 2efc92c2e9..52574c3403 100644 --- a/Recursive/test/BinarySearch.test.js +++ b/Recursive/test/BinarySearch.test.js @@ -7,26 +7,26 @@ describe('BinarySearch', () => { it('should return index 3 for searchValue 10', () => { const searchValue = 10 - expect(binarySearch(arr, low, high, searchValue)).toBe(3) + expect(binarySearch(arr, searchValue, low, high)).toBe(3) }) it('should return index 0 for searchValue 2', () => { const searchValue = 2 - expect(binarySearch(arr, low, high, searchValue)).toBe(0) + expect(binarySearch(arr, searchValue, low, high)).toBe(0) }) it('should return index 13 for searchValue 999', () => { const searchValue = 999 - expect(binarySearch(arr, low, high, searchValue)).toBe(13) + expect(binarySearch(arr, searchValue, low, high)).toBe(13) }) it('should return -1 for searchValue 1', () => { const searchValue = 1 - expect(binarySearch(arr, low, high, searchValue)).toBe(-1) + expect(binarySearch(arr, searchValue, low, high)).toBe(-1) }) it('should return -1 for searchValue 1000', () => { const searchValue = 1000 - expect(binarySearch(arr, low, high, searchValue)).toBe(-1) + expect(binarySearch(arr, searchValue, low, high)).toBe(-1) }) })