JavaScript uses the binary search algorithm to search for data in the array.
This example describes how JavaScript uses the binary search algorithm to search for data in an array. Share it with you for your reference. The specific analysis is as follows:
Binary Search, also known as semi-query, has the advantage of a small number of times, fast query speed, and good average performance. Its disadvantage is that the table to be queried is an ordered table and it is difficult to insert or delete data. Therefore, the half-fold lookup method is suitable for searching frequently ordered lists without frequent changes. First, assume that the elements in the table are arranged in ascending order and the keywords recorded in the middle of the table are compared with the search keywords. If the two are the same, the search is successful; otherwise, the table is divided into the first and last sub-tables by using the intermediate position record. If the keyword recorded in the middle position is greater than the search keyword, the former sub-table is further searched. Otherwise, the latter sub-table is further searched. Repeat the preceding process until you find a record that meets the conditions to make the search successful, or until the child table does not exist, the search fails.
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) return 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 design javascript programs.