Skip to content

Instantly share code, notes, and snippets.

@edrdesigner
Created March 23, 2022 16:12
Show Gist options
  • Save edrdesigner/c27084920f94316b84e586b740b4f96d to your computer and use it in GitHub Desktop.
Save edrdesigner/c27084920f94316b84e586b740b4f96d to your computer and use it in GitHub Desktop.
Binary search algorithm
const arr = ['a','b', 'c', 'd','x', 'y', 'z'];
function findMe(target, start, end) {
if (start > end) return 'not found';
const middle = Math.floor((start+end)/2);
if (arr[middle] === target) {
return `found it at index ${middle}`;
}
if (arr[middle] > target) {
return findMe(target, start, middle-1);
}
if (arr[middle] < target) {
return findMe(target, middle+1, end);
}
}
findMe('c', 0, arr.length);
// found it at index 2
@edrdesigner
Copy link
Author

Code based on fireship video to know more about it. -> https://www.youtube.com/watch?v=MFhxShGxHWc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment