Created
November 20, 2019 03:28
-
-
Save aabir/30c1a81ac61728e9c92baf25fea9e38d to your computer and use it in GitHub Desktop.
Binary Search in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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