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