Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Last active July 10, 2022 16:55
Show Gist options
  • Save helabenkhalfallah/8089b5223736550c8fb0be9ea8ecd891 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/8089b5223736550c8fb0be9ea8ecd891 to your computer and use it in GitHub Desktop.
Vintage Binary Search
// binary search need a pre-sorted array
const binarySearch = (items, itemToFind, start, end) => {
// Base Condition
if (start > end) return null;
// Find the middle index
const mid = Math.floor((start + end) / 2);
// Compare mid with given key itemToFind
if (items[mid] === itemToFind) return mid;
// If element at mid is greater than itemToFind,
// search in the left half of mid
if (items[mid] > itemToFind)
return binarySearch(items, itemToFind, start, mid - 1);
else
// If element at mid is smaller than itemToFind,
// search in the right half of mid
return binarySearch(items, itemToFind, mid + 1, end);
};
const tab = [10, 11, 12, 13, 14, 15, 16];
const start = 0;
const end = tab.length - 1;
const elementToFind = 11;
const elementIndex = binarySearch(tab, elementToFind, start, end);
console.log('element index : ', elementIndex);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment