二分法
public class ErFenFa {
// 递归二分法查找
public int RunOfRe(int[] a, int start, int end, int flag) {
int mid = (end - start) / 2 + start;
if (flag > a[mid]) {
return RunOfRe(a, start + 1, end, flag);
}
if (flag < a[mid]) {
return RunOfRe(a, start, end - 1, flag);
}
if (flag == a[mid]) {
System.out.println("递归二分法查找结果为:");
System.err.println("已找到");
return mid;
}
if (flag > a[end] || flag < a[start]) {
System.out.println("递归二分法查找结果为:");
System.out.println("找不到");
return -1;
}
return 0;
}
// 非递归二分法查找
public int RunOfNotRe(int[] a, int flag) {
int start = 0;
int end = a.length - 1;
while (start <= end) {
int mid = (end - start) / 2 + start;
if (flag > a[mid]) {
start++;
}
if (flag < a[mid]) {
end--;
}
if (flag == a[mid]) {
System.out.println("非递归二分法查找结果为:");
System.out.println("找到了");
break;
}
if (flag > a[end] || flag < a[start]) {
System.out.println("非递归二分法查找结果为:");
System.out.println("找不到");
break;
}
}
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 3, 5, 11, 17, 21, 23, 28, 30, 32, 50, 64, 78, 81, 95, 101 };
int start = 0;
int end = a.length - 1;
// new ErFenFa().RunOfRe(a, start, end, 78);
new ErFenFa().RunOfNotRe(a, 82);
}
}