public class BinarySearch {
public static void main(String[] args) {
int a[] = new int[] { 1, 2, 3, 5, 6, 8, 10, 13, 15 };
System.out.println(binSearch1(a, 0, a.length - 1, 11));
System.out.println(binSearch2(a, 0, a.length - 1, 11));
}
// 递归查找
public static int binSearch1(int[] a, int start, int end, int target) {
int temp = (start + end) / 2;
while (start <= end) {
if (target == a[temp]) {
return temp;
} else if (target < a[temp]) {
return binSearch1(a, start, temp - 1, target);
} else {
return binSearch1(a, temp + 1, end, target);
}
}
return -1;
}
// 非递归查找
public static int binSearch2(int[] a, int start, int end, int target) {
while (start <= end) {
int temp = (start + end) / 2;
if (a[temp] == target) {
return temp;
} else if (target < a[temp]) {
end = temp - 1;
} else {
start = temp + 1;
}
}
return -1;
}
}