Home > Web Front-end > JS Tutorial > JavaScript uses binary search algorithm to find data in an array_javascript tips

JavaScript uses binary search algorithm to find data in an array_javascript tips

WBOY
Release: 2016-05-16 16:05:22
Original
1174 people have browsed it

The example in this article describes how JavaScript uses the binary search algorithm to find data in an array. Share it with everyone for your reference. The specific analysis is as follows:

Binary search, also known as half search, has the advantages of fewer comparisons, fast search speed, and good average performance; its disadvantage is that the table to be looked up is required to be an ordered table, and insertion and deletion are difficult. Therefore, the binary search method is suitable for ordered lists that do not change frequently but are searched frequently. First, assuming that the elements in the table are arranged in ascending order, compare the keyword recorded in the middle position of the table with the search keyword. If the two are equal, the search is successful; otherwise, use the middle position record to divide the table into two sub-tables, the first and last. If If the keyword recorded in the middle position is greater than the search keyword, then the previous subtable will be searched further, otherwise the next subtable will be searched further. Repeat the above process until a record that meets the conditions is found, making the search successful, or until the subtable does not exist, in which case 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);
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template