JS binary Lookup algorithm introduction and code sharing
4.1 Binary lookup algorithm The binary lookup, also known as binary lookup, is a search algorithm for finding specific elements in an ordered array.
The lookup process can be divided into the following steps: (1) First, start the search from the element in the middle of an ordered array, and if the element is exactly the target element (that is, the element to find), the search process ends, otherwise the next step is done.
(2) If the target element is greater than or less than the intermediate element, it looks in the half of the array that is greater than or less than the middle element, and then repeats the first step.
(3) If a step array is empty, the target element is not found.
Reference code: Non-recursive algorithm function Binary_search (arr,key) {var low=0, high=arr.length-1;
while (Low<=high) {var mid=parseint (High+low)/2);
if (Key==arr[mid]) {return mid;
}else if (Key>arr[mid]) {low=mid+1;
}else if (Key<arr[mid]) {high=mid-1;
}else{return-1;
}
}
};
var arr=[1,2,3,4,5,6,7,8,9,10,11,23,44,86];
var result=binary_search (arr,10); alert (result);
9 returns the index value of the target element recursive algorithm function Binary_search (arr,low,high,key) {if (Low>high) {return-1;
var mid=parseint ((High+low)/2);
if (Arr[mid]==key) {return mid;
}else if (arr[mid]>key) {high=mid-1;
Return Binary_search (Arr,low,high,key);
}else if (arr[mid]<key) {low=mid+1;
Return Binary_search (Arr,low,high,key);
}
}; var arr=[1,2,3,4,5,6,7,8,9,10,11,23,44,86];
var result=binary_search (arr,0,13,10); alert (result); 9 returns the index value of the target element author: Geek Tutorial Source: The Nuggets copyright belongs to the author. Commercial reprint please contact the author to obtain authorization, non-commercial reprint please indicate the source.