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