1. Two points lookup is also called binary lookup, it is a more efficient way to find.
2. Two-point lookup requirements: (1) The sequential storage structure (2) must be used. Must be sorted by keyword size
3. Principle: The array is divided into three parts, followed by the median (the so-called median is the middle of the array of values) before, median, median, the value to be looked up and the median value of the array, if less than the median value in front of the median value is found, if the value is greater than the median value is returned after the median Then there is a recursive procedure, in which the first half or the second part continues to be decomposed into three parts.
4. Implementation: Binary lookup implementation by recursion and loop two ways
Public classBinarySearch {/*** Cyclic implementation of binary search algorithm * *@paramarr has a sorted array *@paramnumber of data to find *@returnThe number that needs to be searched is indexed in the array, and no data is returned-1*/ Public Static intBinarySearch (int[] arr,intdata) { intBeginindex = 0; intEndIndex = arr.length-1; while((Beginindex <= endIndex) && (beginindex <= arr.length-1) && (EndIndex <= arr.length-1)) { intMidindex = (beginindex + endIndex)/2; if(Data = =Arr[midindex]) { returnMidindex; } Else if(Data <Arr[midindex]) {EndIndex= MidIndex-1; } Else{beginindex= Midindex + 1; } } return-1; } /*** Recursive implementation of binary search * *@paramarr has a sorted array *@paramnumber of data to find *@parambeginindex Start Index *@paramEndIndex End Index *@returnThe number that needs to be searched is indexed in the array, and no data is returned-1*/ Public Static intBinarySearch (int[] arr,intDataintBeginindex,intEndIndex) { intMidindex = (beginindex + endIndex)/2; if(Data < Arr[beginindex] | | data > ARR[ENDINDEX] | | beginindex >EndIndex) { return-1; } if(Data <Arr[midindex]) { returnBinarySearch (arr, data, Beginindex, midIndex-1); } Else if(Data >Arr[midindex]) { returnBinarySearch (arr, data, Midindex + 1, EndIndex); } Else { returnMidindex; } } Public Static voidMain (string[] args) {int[] arr = {6, 12, 33, 87, 90, 97, 108, 561}; //3System.out.println ("Loop lookup:" + binarysearch (arr, 87)); //3SYSTEM.OUT.PRINTLN ("Recursive lookup" + binarysearch (arr, 0, Arr.length-1)); }}
Binary lookup Algorithm (JAVA)