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.