Array.prototype.binarySearch = function (obj)
{
var value = 0;
var left = 0;
var right= this.length;
while (left <= right)
{
var center = Math.floor ((left+right)/2);
if (this[center] = obj)
{
value = center;
}
if (obj < This[center])
{
right = center-1;
}
Else
{
Left = center + 1;
}
}
alert (value);
}
//Following is the test code:
Function Testarraybinarysearch ()
{
var array = new Array ();
var key = 678;
var number = 1000;
for (i = 0; i < number; i++)
{
Array.push (i);
}
Array.BinarySearch (key);
}
Window.onload = function ()
{
Testarraybinarysearch ();
}
Here is the foreign code
JavaScript Tutorials//copyright 2009 Nicholas C. Zakas. All rights reserved.
mit-licensed, the source file
Copy code code as follows:
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 (adjust lookup range)
if (value < Items[middle]) {
Stopindex = middle-1;
else if (value > Items[middle]) {
StartIndex = middle + 1;
}
Recalculate Middle (re-evaluates the index of the item)
Middle = Math.floor ((stopindex + startIndex)/2);
}
Make sure it's right value (ensure that the correct value is returned)
Return (Items[middle]!= value)? -1:middle; }