1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
package junit.test;
public class BinarySearchTest {
public int binarySearch(int dataset[],int target,int beginIndex,int endIndex){ if(dataset==null||dataset.length==0){ return -1; } if(beginIndex>endIndex||beginIndex>dataset.length-1||endIndex>dataset.length-1||beginIndex<0||endIndex<0){ System.out.println("error arguments!"); return -1; } if(target<dataset[beginIndex]||target>dataset[endIndex]||beginIndex>endIndex){ return -1; } int midIndex=(beginIndex+endIndex)/2; if(target==dataset[midIndex]){ return midIndex; } else if(target<dataset[midIndex]){ return binarySearch(dataset,target,beginIndex,midIndex-1); } else{ return binarySearch(dataset,target,midIndex+1,endIndex); } }
public static void main(String[] args) { BinarySearchTest bs=new BinarySearchTest(); int[] data=new int[]{1,3,5,7,9,12}; int index=bs.binarySearch(data,12,0, 5); System.out.println("The position of the target number in the array is :"+ index); }
}
|