Skip to content

Instantly share code, notes, and snippets.

@shadow1349
Created February 24, 2023 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadow1349/22f3747c5a91aa753cbec37385bfa349 to your computer and use it in GitHub Desktop.
Save shadow1349/22f3747c5a91aa753cbec37385bfa349 to your computer and use it in GitHub Desktop.
// 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