package basic.alg;
public class BinarySearch {
/**
* 二分查找递归实现
*
*
* */
public static int binarySearch(int[] arr, int low, int high, int t) {
if (t > arr[high] || t < arr[low]) {
throw new RuntimeException("不存在要查找的元素");
}
if (high == low) {
if (arr[high] != t) {
throw new RuntimeException("不存在要查找的元素");
}
return high;
}
//中位数
int mid = (low + high) / 2;
if (arr[mid] == t) {
return mid;
} else if (arr[mid] > t) {
//如果剩下两个数,因为整数的除法总是取较小的数,所以要判断中位数是否小于低位数
high = (mid - 1) < low? low : mid - 1;
return binarySearch(arr, low, high, t);
} else {
return binarySearch(arr, mid + 1, high, t);
}
}
/**
* 二分查找循环实现
*
* */
public static int binarySearch(int[] arr, int t) {
if (arr[0] > t || arr[arr.length - 1] < t) {
throw new RuntimeException("不存在查找的数");
}
int low = 0, high = arr.length - 1;
int mid = (low + high) / 2;
if (arr[mid] == t) {
return mid;
}
while (high > low) {
mid = (low + high) / 2;
if (arr[mid] == t) {
break;
} else if (arr[mid] > t) {
// high = (mid - 1) > low? mid - 1 : low;
high = (mid - 1);
} else {
low = mid + 1;
}
}
if (high > low) {
return mid;
} else {
if (arr[high] != t) {
throw new RuntimeException("不存在查找的数");
}
return high;
}
}
public static void main(String[] args) throws InterruptedException {
int t1 = 1;
int t2 = 5;
int t3 = 9;
int t4 = 4;
int t5 = 2;
int[] arr = {1,2,3,5,6,7,8,9,};
// System.out.println("t1: " + t1 + ", result: " + binarySearch(arr, 0, arr.length -1, t1));
// System.out.println("t2: " + t2 + ", result: " + binarySearch(arr, 0, arr.length -1, t2));
// System.out.println("t3: " + t3 + ", result: " + binarySearch(arr, 0, arr.length -1, t3));
// System.out.println("t5: " + t5 + ", result: " + binarySearch(arr, 0, arr.length -1, t5));
// System.out.println("t4: " + t4 + ", result: " + binarySearch(arr, 0, arr.length -1, t4));
System.out.println("t1: " + t1 + ", result: " + binarySearch(arr, t1));
System.out.println("t2: " + t2 + ", result: " + binarySearch(arr, t2));
System.out.println("t3: " + t3 + ", result: " + binarySearch(arr, t3));
System.out.println("t5: " + t5 + ", result: " + binarySearch(arr, t5));
Thread.sleep(1000);
System.out.println("t4: " + t4 + ", result: " + binarySearch(arr, t4));
}
}