merge: binarySearch (#884)

* required, optional param left-to-right approch in BS

* base case return early to avoid nested if block

* codes formated with standard.js
This commit is contained in:
Keramot UL Islam
2022-02-16 14:54:32 +06:00
committed by GitHub
parent c496925d25
commit 833d05d8d0
2 changed files with 20 additions and 22 deletions

View File

@ -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)
}
// Else the element can only be present in right subarray
return binarySearch(arr, mid + 1, high, searchValue)
// If the element is present at the middle
if (arr[mid] === searchValue) {
return mid
}
// We reach here when element is not present in array
return -1
// 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)
}
// Else the element can only be present in right subarray
return binarySearch(arr, searchValue, mid + 1, high)
}
export { binarySearch }

View File

@ -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)
})
})