Created
June 23, 2023 15:19
-
-
Save ericviana/d77423e4f9b9a4a79d7d23c23767d025 to your computer and use it in GitHub Desktop.
Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function binarySearch(arr, target) { | |
let left = 0; | |
let right = arr.length - 1; | |
while (left <= right) { | |
let mid = Math.floor((left + right) / 2); | |
if (arr[mid] === target) { | |
return mid; | |
} else if (arr[mid] < target) { | |
left = mid + 1; | |
} else { | |
right = mid - 1; | |
} | |
} | |
return -1; | |
} | |
const array = [1, 3, 5, 7, 9]; | |
console.log(binarySearch(array, 5)); // Output: 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment