JavaScript binary (array arrays) _javascript tips

Source: Internet
Author: User
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;
}
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.