Skip to content

Add proper tests for binary search #987

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 21, 2022
Merged
Changes from 5 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
25 changes: 24 additions & 1 deletion Search/BinarySearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,25 @@ function binarySearchIterative (arr, x, low = 0, high = arr.length - 1) {
// if low > high => we have searched the whole array without finding the item
return -1
}
function binarySearchIterativeAlternative (arr, x) {
let low = -1
let high = arr.length
while (low < high - 1) {
const mid = Math.floor((low + high) / 2)
if (arr[mid] < x) {
low = mid
} else {
high = mid
}
}
return arr[high] === x ? high : -1
}

export { binarySearchIterative, binarySearchRecursive }
export {
binarySearchIterative,
binarySearchIterativeAlternative,
binarySearchRecursive
}

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

Expand Down Expand Up @@ -89,3 +106,9 @@ export { binarySearchIterative, binarySearchRecursive }
// binarySearchIterative(stringArr, 'Charlie')
// binarySearchRecursive(stringArr, 'Zulu')
// binarySearchIterative(stringArr, 'Sierra')
// binarySearchIterativeAlternative(arr, 3)
// binarySearchIterativeAlternative(arr, 7)
// binarySearchIterativeAlternative(arr, 13)
// binarySearchIterativeAlternative(stringArr, 'Charlie')
// binarySearchIterativeAlternative(stringArr, 'Zulu')
// binarySearchIterativeAlternative(stringArr, 'Sierra')