In JavaScript, we can add new attributes or methods to an object by using the prototype keyword, and here is a way to add a binary lookup function for an array object:
Copy Code code as follows:
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);
}
The 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 binary//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;
}