package com.gui.erfen;
public class erfenSearch {
/**
* 二分查找
*/
public static void main(String[] args) {
int[] a = new int[] { 3, 11, 34, 56, 72, 88, 90, 110 };
int oneTarget = 72;
int twoTarget = 50;
int oneResult = buggyBinarySearch(a, oneTarget);
int twoResult = buggyBinarySearch(a, twoTarget);
System.out.println("要查找的元素" + oneTarget + "在数组中的下标为:" + oneResult);
System.out.println("要查找的元素" + twoTarget + "在数组中的下标为:" + twoResult
+ (twoResult == -1 ? ",该元素在数组中不存在" : ""));
}
public static int buggyBinarySearch(int[] a, int target) {
// 进行二分法查找的前提是数字已经排好序的,并且升序。
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;// 存在经典的bug
int midVal = a[mid];
if (midVal < target)
low = mid + 1;
else if (midVal > target)
high = mid - 1;
else
return mid;
}
return -1;
}
}
public class erfenSearch {
/**
* 二分查找
*/
public static void main(String[] args) {
int[] a = new int[] { 3, 11, 34, 56, 72, 88, 90, 110 };
int oneTarget = 72;
int twoTarget = 50;
int oneResult = buggyBinarySearch(a, oneTarget);
int twoResult = buggyBinarySearch(a, twoTarget);
System.out.println("要查找的元素" + oneTarget + "在数组中的下标为:" + oneResult);
System.out.println("要查找的元素" + twoTarget + "在数组中的下标为:" + twoResult
+ (twoResult == -1 ? ",该元素在数组中不存在" : ""));
}
public static int buggyBinarySearch(int[] a, int target) {
// 进行二分法查找的前提是数字已经排好序的,并且升序。
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;// 存在经典的bug
int midVal = a[mid];
if (midVal < target)
low = mid + 1;
else if (midVal > target)
high = mid - 1;
else
return mid;
}
return -1;
}
}