The two-point lookup must be ordered in order to find the premises of the array.
The code is as follows:
Procedure 1
1 Public classSource {2 3 Public intBinary_sort (int[] Array,intItem) {4 intLen =Array.Length;5 intmin = 0;//define the start of a lookup range6 intmax = len-1;//defines the end of a lookup range7 while(Max > min) {//This can't be equal, or it could be a dead loop.8 if(array[min+ (Max-min)/2] = =Item) {9 return(int) min+ (max-min)/2;Ten } One Else if(array[min+ (Max-min)/2] >Item) { Amax = min+ (max-min)/2; - } - Else if(array[min+ (Max-min)/2] <Item) { themin = min+ (max-min)/2; - } - } - return-1; + } - + Public Static voidMain (string[] args) { A int[] A = {1,2,3,4,5,6,7,8,9,10}; at intn =-1; -SOURCE Sou =Newsource (); - System.out.println (Sou.binary_sort (A, n)); - } -}
The program can be copied down to normal execution, this is the principle of their own read the code, the Internet to find an example, also posted to compare
Procedure 2
1 intBinary_sort (intArray[],intLengthintvalue)2 { 3 if(NULL = = Array | |0==length)4 return-1; 5 6 intStart =0; 7 intEnd = Length-1; 8 9 while(Start <=end) { Ten One intMiddle = start + ((End-start) >>1); A if(Value = =Array[middle]) - returnMiddle; - Else if(Value >Array[middle]) { theStart = middle +1; -}Else{ -End = Middle-1; - } + } - + return-1; A}
The problem of finding your own code in contrast to someone else's code:
1. Complex expression variables should be defined as variables.
2. In program 1, there is no max = Len, no minus one, the array subscript problem should be noted. The following two lines of code.
3. Program 2 calculates that the mean is not directly divided by 2, but rather (End-start) >> 1, with a shift operation, which avoids generating decimals and does not force type conversions.
Two-point Search