JavaScript uses a binary lookup algorithm to find data in an array _javascript tips

Source: Internet
Author: User

This article illustrates how JavaScript uses the binary lookup algorithm to find data in an array. Share to everyone for your reference. The specific analysis is as follows:

Binary search, also known as binary search, the advantage is that the comparison of less times, the search speed, average performance is good; its disadvantage is that the table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for frequently ordered lists that are infrequently changed. First, suppose that the elements in the table are sorted in ascending order, compares the keywords in the middle position record of the table to the lookup key, and if the two are equal, the search succeeds; otherwise, the table is divided into the preceding and the last two child tables using the middle position record, and the previous child table is further searched if the key of the middle position record is greater than the lookup keyword Otherwise, the next child table is further searched. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful.

var Arr = [3,5,6,7,9,12,15];
function binary (find,arr,low,high) {
if (low <= high) {
if (arr[low] = = find) return to low
;
if (arr[high] = = find) return to high
;
var mid = Math.ceil ((high + Low)/2);
if (arr[mid] = = Find) {return
mid;
} else if (Arr[mid] > Find) {return
binary (find,arr,low,mid-1);
} else{return
binary (find,arr,mid+1,high);
}
return-1;
}
Binary (15,arr,0,arr.length-1);

I hope this article will help you with your JavaScript programming.

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.