Tag: String Public cannot data PAC binary INI begin while
1, two-part search algorithm
Package Other;public class BinarySearch {/* * Loop implementation binary lookup algorithm arr ordered array x number of lookups required-1 Unable to find data */public static int B Inarysearch (int[] arr, int x) {int low = 0; int high = arr.length-1; while (low <= high) {int middle = (low + high)/2; if (x = = Arr[middle]) {return middle; }else if (x <arr[middle]) {high = middle-1; }else {low = middle + 1; }} return-1; }//Recursive implementation Two-point lookup public static int BinarySearch (int[] dataset,int data,int beginindex,int endIndex) {int m Idindex = (beginindex+endindex)/2; if (Data <dataset[beginindex]| | data>dataset[endindex]| | Beginindex>endindex) {return-1; } if (data <dataset[midindex]) {return binarysearch (dataset,data,beginindex,midindex-1); }else if (data>dataSet[midindex]) {return binarysearch (Dataset,data,midindex+1,endindex); }else {return midindex; }} public static void Main (string[] args) {int[] arr = {6, 12, 33, 87, 90, 97, 108, 561}; System.out.println ("Loop lookup:" + (BinarySearch (arr, 87) + 1)); SYSTEM.OUT.PRINTLN ("Recursive lookup" +binarysearch (arr,3,87,arr.length-1)); }}
Complexity of Time
For example: There is a total of n elements, the interval size of each lookup is n,n/2,n/4,...,n/2^k (the remaining number of elements to be manipulated), where K is the number of cycles.
Since N/2^k >=1, even if n/2^k=1,
Can be k=log2n, (is the logarithm of the base 2, N), so the time complexity can represent O () =o (LOGN)
Lookup algorithm (Java implementation)