Created
February 24, 2023 00:16
-
-
Save shadow1349/22f3747c5a91aa753cbec37385bfa349 to your computer and use it in GitHub Desktop.
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
// create a binary search function that takes in a non-sorted array and a target value | |
const binarySearch = (arr: number[], target: number) => { | |
// sort the array | |
arr.sort((a, b) => a - b); | |
// create a left and right pointer | |
let left = 0; | |
let right = arr.length - 1; | |
// loop while left is less than or equal to right | |
while (left <= right) { | |
// create a middle pointer | |
const middle = Math.floor((left + right) / 2); | |
// if the target is at the middle, return the middle | |
if (arr[middle] === target) return middle; | |
// if the target is greater than the middle, move the left pointer up | |
if (arr[middle] < target) left = middle + 1; | |
// if the target is less than the middle, move the right pointer down | |
if (arr[middle] > target) right = middle - 1; | |
} | |
// if the target doesn't exist in the array, return -1 | |
return -1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment