programming-examples/js/Array/Write a JavaScript program to perform a binary search..js

23 lines
758 B
JavaScript
Raw Normal View History

2019-11-15 12:59:38 +01:00
function binary_Search(items, value){
var firstIndex = 0,
lastIndex = items.length - 1,
middleIndex = Math.floor((lastIndex + firstIndex)/2);
while(items[middleIndex] != value && firstIndex < lastIndex)
{
if (value < items[middleIndex])
{
lastIndex = middleIndex - 1;
}
else if (value > items[middleIndex])
{
firstIndex = middleIndex + 1;
}
middleIndex = Math.floor((lastIndex + firstIndex)/2);
}
return (items[middleIndex] != value) ? -1 : middleIndex;
}
var items = [1, 2, 3, 4, 5, 7, 8, 9];
console.log(binary_Search(items, 1));
console.log(binary_Search(items, 5));