Skip to content

Instantly share code, notes, and snippets.

@aabir
Created November 20, 2019 03:28
Show Gist options
  • Save aabir/30c1a81ac61728e9c92baf25fea9e38d to your computer and use it in GitHub Desktop.
Save aabir/30c1a81ac61728e9c92baf25fea9e38d to your computer and use it in GitHub Desktop.
Binary Search in JavaScript
function binarySearch(sortedArry, itemToFind)
{
var minIndex = 0;
var maxIndex = sortedArry.length - 1;
while (minIndex <= maxIndex)
{
var midIndex = Math.floor((minIndex + maxIndex) / 2);
if(sortedArry[midIndex] == itemToFind)
{
return midIndex;
}
else if (sortedArry[midIndex] < itemToFind)
{
minIndex = midIndex + 1;
} else {
maxIndex = midIndex - 1;
}
}
return null;
}
var arry = ["blue", "green", "indigo", "orange", "red", "violet", "yellow"];
var sortedArry = arry.sort();
console.log(binarySearch(sortedArry, "yellow"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment