Java record-37-Binary Search

Source: Internet
Author: User

Java record-37-Binary Search
Binary Search, also known as Binary Search, has the advantage of a small number of queries, fast query speed, and good average performance. Its disadvantage is that the table to be queried must be an ordered table and it is difficult to insert or delete data. Therefore, the half-fold lookup method is suitable for searching frequently ordered lists without frequent changes. First, assume that the elements in the table are arranged in ascending order and the keywords recorded in the middle of the table are compared with the search keywords. If the two are the same, the search is successful; otherwise, the table is divided into the first and last sub-tables by using the intermediate position record. If the keyword recorded in the middle position is greater than the search keyword, the former sub-table is further searched. Otherwise, the latter sub-table is further searched. Repeat the preceding process until you find a record that meets the conditions to make the search successful, or until the child table does not exist, the search fails.

Public class BinarySearchTest {private static int binarySearch (int [] array, int value) {int low = 0, high = array. length-1, middle = 0; while (low <= high) {middle = (low + high)/2; /* print the median (int I = 0; I <array. length; I ++) {System. out. print (array [I]); if (I = middle) {System. out. print ("#");} System. out. print ("");} System. out. println (); */if (array [middle] = value) {return middle;} if (array [middle]> value) {high = middle-1 ;} if (array [middle] <value) {low = middle + 1 ;}}return-1 ;}public static void main (String [] args) {int [] array = {2, 5, 7, 8, 9, 11}; int index = binarySearch (array, 11); System. out. println (index );}}

 

Next article: http://www.bkjia.com/kf/201510/447450.html

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.