package com.sxc.search;
import org.junit.Test;
public class BinarySearch {
public static int[] array = {1,3,5,7,9,15,13,12,10};//待搜索数组
public static int search = 9;//待查找数字
public int getIndex(int begin, int end) {
int middle = begin + (end - begin)/2;
if (array[middle] == search){
return middle;
}else if (end <= begin){
return -1;
}
else {
int lertResult = getIndex(begin, middle - 1);
if (lertResult != -1) {//递归结束条件
return lertResult;
} else {
int rightResult = getIndex(middle + 1, end);//递归实现
if (rightResult != -1) {
return rightResult;
} else {
return -1;
}
}
}
}
@Test
public void test2(){//测试示例
BinarySearch m = new BinarySearch();
int result = m.getIndex(0, array.length-1);
System.out.println(result);//输出9的下标
}
}