Created
August 11, 2018 10:00
-
-
Save zerobias/cef654a17a33eee5fde014b00e3d121d to your computer and use it in GitHub Desktop.
binary search
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
/** | |
* Uses a binary search algorithm to locate a value in the specified array. | |
* @param {Array} items The array containing the item. | |
* @param {variant} value The value to search for. | |
* @return {int} The zero-based index of the value in the array or -1 if not found. | |
*/ | |
function binarySearch(items, value){ | |
var startIndex = 0, | |
stopIndex = items.length - 1, | |
middle = Math.floor((stopIndex + startIndex)/2); | |
while(items[middle] != value && startIndex < stopIndex){ | |
//adjust search area | |
if (value < items[middle]){ | |
stopIndex = middle - 1; | |
} else if (value > items[middle]){ | |
startIndex = middle + 1; | |
} | |
//recalculate middle | |
middle = Math.floor((stopIndex + startIndex)/2); | |
} | |
//make sure it's the right value | |
return (items[middle] != value) ? -1 : middle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment