In JavaScript, we can use the prototype keyword to add new attributes or methods to an object. The following is a method for adding the binary search function to an array object:
CopyCode The Code is 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 ();
}
The following is the foreign code
Javascript bipartite // Copyright 2009 Nicolas C. zakas. All rights reserved.
// Mit-licensed, see source fileCopy codeThe Code is 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 the search range)
If (value <items [Middle]) {
Stopindex = middle-1;
} Else if (value> items [Middle]) {
Startindex = middle + 1;
}
// Recalculate middle (re-calculate the index)
Middle = math. Floor (stopindex + startindex)/2 );
}
// Make sure it's the right value (make sure the correct value is returned)
Return (items [Middle]! = Value )? -1: middle;
}