Find Algorithm (ii) Find by dichotomy

Source: Internet
Author: User

binary search: Required elements must be ordered, and if they are unordered, sort operations first

  The basic idea : also known as binary lookup, belongs to the ordered search algorithm. With the given value K first compared with the middle node of the keyword, the middle node divides the Line table into two sub-tables, if the equality is found successful; if not equal, then according to the comparison between K and the middle node keyword to determine which child table next, so recursively, until the find or find the end of the discovery table does not have such a node.

  complexity Analysis : in the worst case, the number of keyword comparisons is log2 (n+1), and the expected time complexity is O (log2n);

Note: the precondition of binary lookup is that ordered table sequential storage is required, for static lookup table, once sorting no longer changes, binary lookup can get good efficiency. However, for datasets that require frequent insert or delete operations, maintaining an ordered ordering can create a lot of work, and it is not recommended to use

 PackageCom.yyx.searchAlgorithm;Importjava.util.Arrays;/*** dichotomy Find Yyx February 3, 2018*/ Public classBinarySearch { Public Static voidMain (string[] args) {int[] arr = {35, 23, 46, 32, 67, 87 }; //Array SortingArrays.sort (arr);        System.out.println (arrays.tostring (arr)); intValue = 32; intindex =Testsearch (arr, value, arr.length); if(Index = =-1) {System.out.println ("No element Found"); } Else{System.out.println (The index of the lookup element is: "+index); }    }     Public Static intTestsearch (int[] arr,intValueintN) {intLow = 0; intHigh = N-1; intmid;  while(Low <=High ) {Mid= (low + high)/2; if(Arr[mid] = =value) {                returnmid; }            if(Arr[mid] >value) { High= Mid-1; }            if(Arr[mid] <value) { Low= Mid + 1; }        }        return-1; }        }

Find Algorithm (ii) Find by dichotomy

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.