merge: Add test cases, optamization of code, and Add description of function (#848)

* Add test cases, optamization of code, and Add description of function

* update testcase
This commit is contained in:
YATIN KATHURIA
2021-11-26 22:08:43 +05:30
committed by GitHub
parent 8b1a4b90f6
commit 2fb0d48d94
2 changed files with 63 additions and 14 deletions

View File

@@ -1,19 +1,36 @@
// https://en.wikipedia.org/wiki/Binary_search_algorithm
// Search the integer inside the sorted integers array using Binary Search Algorithm
/**
* @function BinarySearch
* @description Search the integer inside the sorted integers array using Binary Search Algorithm.
* @param {Integer[]} arr - sorted array of integers
* @param {Integer} low - The input integer
* @param {Integer} high - The input integer
* @param {Integer} searchValue - The input integer
* @return {Integer} - return index of searchValue if found else return -1.
* @see [BinarySearch](https://en.wikipedia.org/wiki/Binary_search_algorithm)
*/
export const BinarySearch = (intArr, searchQuery) => {
if (searchQuery === null || searchQuery === undefined || intArr.length === 0) {
return false
const binarySearch = (arr, low = 0, high = arr.length - 1, searchValue) => {
if (high >= low) {
const mid = low + Math.floor((high - low) / 2)
// If the element is present at the middle
if (arr[mid] === searchValue) {
return mid
}
// 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)
}
const middleIndex = intArr.length === 1 ? 0 : Math.ceil(intArr.length / 2)
if (intArr[middleIndex] === searchQuery) {
return true
} else if (intArr.length > 1) {
return intArr[middleIndex] < searchQuery ? BinarySearch(intArr.slice(1, middleIndex)) : BinarySearch(intArr.slice(middleIndex))
} else {
return false
}
// We reach here when element is not present in array
return -1
}
export { binarySearch }