Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions Search/BinarySearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* value is found or the interval is empty.
*/

function binarySearch (arr, x, low = 0, high = arr.length - 1) {
function binarySearchRecursive (arr, x, low = 0, high = arr.length - 1) {
const mid = Math.floor(low + (high - low) / 2)

if (high >= low) {
Expand All @@ -18,16 +18,36 @@ function binarySearch (arr, x, low = 0, high = arr.length - 1) {

if (x < arr[mid]) {
// arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
return binarySearch(arr, x, low, mid - 1)
return binarySearchRecursive(arr, x, low, mid - 1)
} else {
// arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
return binarySearch(arr, x, mid + 1, high)
return binarySearchRecursive(arr, x, mid + 1, high)
}
} else {
// if low > high => we have searched the whole array without finding the item
return -1
}
}
function binarySearchIterative (arr, x, low = 0, high = arr.length - 1) {
while (high >= low) {
const mid = Math.floor(low + (high - low) / 2)

if (arr[mid] === x) {
// item found => return its index
return mid
}

if (x < arr[mid]) {
// arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
high = mid - 1
} else {
// arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
low = mid + 1
}
}
// if low > high => we have searched the whole array without finding the item
return -1
}

/* ---------------------------------- Test ---------------------------------- */

Expand Down Expand Up @@ -61,10 +81,10 @@ const stringArr = [
'Zulu'
]

console.log(binarySearch(arr, 3))
console.log(binarySearch(arr, 7))
console.log(binarySearch(arr, 13))
console.log(binarySearchRecursive(arr, 3))
console.log(binarySearchIterative(arr, 7))
console.log(binarySearchRecursive(arr, 13))

console.log(binarySearch(stringArr, 'Charlie'))
console.log(binarySearch(stringArr, 'Zulu'))
console.log(binarySearch(stringArr, 'Sierra'))
console.log(binarySearchIterative(stringArr, 'Charlie'))
console.log(binarySearchRecursive(stringArr, 'Zulu'))
console.log(binarySearchIterative(stringArr, 'Sierra'))