Implementing binary Lookups with Java
Basic idea: While recursive loop, constantly judge A[middle] is equal to data, if it is equal to jump out of the loop, return the index value, if not equal, until the two are equal, where the Count counter records the number of lookups, Considered an element does not exist when count is more than 20 times (here to be optimized)
Packagetest;/** Binary search (binary find) * tgmoving **/ Public classHalfsearch { Public Static intHalfsearch (intA[],intdata) { intLength =a.length; intStart = 0; intEnd = Length-1; intMiddle = (start + end)/2; intCount = 1;//used for counting, binary lookups more than 20 times still not found as this element does not exist while(data!=A[middle]) { if(Start > End | | count > 20){ return-1; }Else{ if(Data <A[middle]) {End=Middle; Middle= (start + end)/2; System.out.println ("+" + (count+1) + "search data < A[middle]:" + "index:" +middle); }Else if(Data >A[middle]) {Start= middle + 1; Middle= (start + end)/2; System.out.println ("+" + (count+1) + "search data > A[middle]:" + "index:" +middle); }} Count++; } Count= 0; returnMiddle; } Public Static voidMain (String[]args) {intA[] = {1,2,3,4,5,6,7}; intindex = Halfsearch (A, 7); System.out.println ("Isexist:" +index); }}
Running results show:
Java Implementation Binary lookup (dichotomy)