JS Binary Lookup algorithm introduction and code sharing __ static functions

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.