Binary Search, also known as semi-query, has the advantage of a small number of times, fast query speed, and good average performance. Its disadvantage is that the table to be queried is 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.
Since this algorithm is easy to understand, I will not say much about it ..
Recursive Implementation:
Package hello. ant; public class AlogBinarySearch2 {public static void main (String [] args) {int array [] = {1, 2, 3, 5, 6, 8, 9}; int pos = binarySearch (array, 0, array. length-1, 8); System. out. println (pos);} static int binarySearch (int [] array, int begin, int end, int x) {int mid = 0; if (begin> end) {return-1;} else {mid = (begin + end)/2; System. out. println ("mid =" + mid); if (x = array [mid]) {return mid;} else if (x
Result:Mid = 3
Mid = 5
5
Non-Recursive Implementation:
package hello.ant;public class AlogBinarySearch {public static void main(String[] args) {int array[]={1,2,3,5,6,8,9};int pos=binarySearch(array,7);System.out.println(pos);}static int binarySearch(int[] array, int x) {int begin=0,end=array.length-1;int mid=0;while(begin<=end){mid=(begin+end)/2;System.out.println("mid=="+mid);if(x==array[mid]){return mid;}else if(x
mid==3
mid==5
mid==4
4
-1