Skip to content

Instantly share code, notes, and snippets.

@ardenn
Created January 24, 2019 20:27
Show Gist options
  • Save ardenn/56523d3ad42e302f7f467628400fa939 to your computer and use it in GitHub Desktop.
Save ardenn/56523d3ad42e302f7f467628400fa939 to your computer and use it in GitHub Desktop.
// A function that takes 2 arguments: an array and a value to search in the array
function binarySearch(arr, target) {
// make a copy of the array and sort it so that we can perform binary search
const sortedArray = [...arr];
sortedArray.sort();
let mid;
let start = 0;
let end = arr.length - 1;
while (start <= end) {
mid = Math.floor((start + end) / 2);
if (sortedArray[mid] === target) {
// get the position of target in the original array
return arr.indexOf(sortedArray[mid]);
}
if (sortedArray[mid] > target) {
end = mid - 1;
}
if (sortedArray[mid] < target) {
start = mid + 1;
}
}
return -1;
}
console.log(binarySearch([5, 6, 7, 7, 4, 8], 100))
console.log(binarySearch([5, 6, 7, 7, 4, 8], 7))
console.log(binarySearch([5, 6, 7, 7, 4, 8], 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment