Lookup algorithm (Java implementation)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.