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:
Copy codeThe 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 file
Copy 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;
}