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

Source: Internet
Author: User

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 var Arr = [3,5,6,7,9,12,15]; function binary (Find,arr,low,high) {if (low <= high) {if (arr[low] = = find) return low; if (arr[high] = = find) ; 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);
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.