Javascript binary (array) _ javascript skills

Source: Internet
Author: User
Extends the Array object and adds the binary search function to it to improve the search efficiency. 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:

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 file

The 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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.