/ ** * Conditions: * 1, the binary search must be sequentially stored results * 2 keywords must order * / public class TestBinarySearch { public static void main (String [] args) { // definition of an array int [] = {11,21,31,41,51,61,71,81,91 ARR }; System.out.println ( "non-recursive:" + binarySearch (ARR, 61 is )); System.out.println ( " recursive: "+ recursionSearch (ARR, 0, arr.length - 1,61 )); } / ** * non-recursive * / static int binarySearch ( int [] ARR, int Key) { // defines the start and end value index int Start = 0 ; int End arr.length = -. 1 ; // determination start value of the index before the index value was greater than the end lookup to find the while (Start <= End) { // definition of intermediate index int MID = (Start + End ) / 2 ; // if the intermediate element value corresponding to the index is equal to the target value, an intermediate value of the index returns directly IF (ARR [mID] == Key) { return mID; // intermediate value is greater than the target value, the target value described at the beginning between the index value and the end value becomes an intermediate value. 1-mID } the else IF (ARR [mID]> Key) { end = mID -. 1 ; // the other hand, between the intermediate target value and the end value, the start value of the index +. 1 becomes MID } the else{ Start = MID +. 1 ; } } // find not return -1 return -1 ; } / ** * Recursive * / static int recursionSearch ( int [] ARR, int Start, int End, int Key) { / / intermediate value index int mID = (start + End) / 2 ; // recursive start condition the while (start <= End) { // intermediate value is equal to the target value, an intermediate value of the index returns directly IF (ARR [mID] == Key ) { return MID; }the else IF (ARR [MID]> Key) { // intermediate value becomes larger than the target value of the index end mid-1, recursively find return recursionSearch (ARR, Start, MID -. 1 , Key); } the else { // intermediate less than the target value, the start value of the index becomes mid + 1, recursively find return recursionSearch (ARR,. 1 + MID , end, Key); } } // recursive end not found return -1 return -1 ; } }
operation result: