Binary search also known as binary lookup, the advantages are less than the number of comparisons, Find Fast, the average performance is good, the disadvantage is that the unknown origin table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent. First, suppose that the elements in the table are arranged in ascending order, comparing the keywords in the middle position of the table with the lookup keywords, and if they are equal, the lookup succeeds; otherwise, the table is divided into the front and the last two sub-tables with the intermediate positional records, and if the middle position record keyword is greater than the Find keyword, the previous child Otherwise, find the latter child table further. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful at this time.
The condition is: 1. Sequential storage structure must be used
2. Must be sorted by keyword size.
Here's a look at the code:
Public class binarysearch { /** * Non-recursive method, using while loop * @param arr * @param des * @return */ Public Static int BinarySearch(int[] arr,intDES) {intLow =0;intHigh = arr.length-1; while(Low<=high) {intMiddle = (Low+high)/2;if(Arr[middle] = = des) {returnMiddle; }Else if(Arr[middle]<des) {low = Middle+1; }Else{high = middle-1; } }return-1; }/** * Recursive lookup * @param arr * @param des * @param low * @param High * @return * / Public Static int BinarySearch(int[] arr,intDesintLowintHigh) {intMiddle = (Low+high)/2;if(des<arr[low]| | des>arr[high]| | Low>high) {return-1; }if(Arr[middle]<des) {returnBinarySearch (arr, DES, middle+1, high); }Else if(Arr[middle]>des) {returnBinarySearch (arr, des, Low, middle-1); }Else{returnMiddle; } } Public Static void Main(string[] args) {int[] arr = {1,2,3,4,5,6,7,8, One, the, -};intDes = the; System.out.println (BinarySearch (arr, des)); System.out.println (BinarySearch (arr, DES,0,Ten)); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Two ways to implement binary lookups (JAVA)