# JavaScript is a method of finding data in an array using a binary search algorithm

- 2020-05-27 04:14:28
- OfStack

This example shows how JavaScript USES a two-point lookup algorithm to find data in an array. Share with you for your reference. The specific analysis is as follows:

2 points search also known as broken half search, the advantage is less times, search speed, the average performance is good; The disadvantage is that it requires the waiting table to be an ordered table, and it is difficult to insert and delete. Therefore, the binary search method is suitable for frequent ordered lists that do not change frequently. First, assuming that the elements in the table are arranged in ascending order, the keywords of the records in the middle of the table are compared with the search keywords. If they are equal, the search is successful. Otherwise, the middle position record is used to divide the table into two sub-tables. If the keyword of the middle position record is greater than the search keyword, the first sub-table will be searched one step ahead, otherwise, the second sub-table will be searched one step ahead. Repeat the process until you find a record that meets the criteria to make the lookup successful, or until the subtable does not exist and 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 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 has been helpful to your javascript programming.