package sort;
public class BinarySearch {
public static void main(String[] args) {
int arr[] = {1, 3, 4, 5, 13, 14, 20, 25, 58};
int index = binarySearch(arr, 0, arr.length - 1, 1);
if (index == -1) {
System.out.println("1 is not found");
} else {
System.out.printf("Found 1 in arr[%d]\n", index);
}
index = binarysearchNoRecursion(arr, 1);
if (index == -1) {
System.out.println("1 is not found");
} else {
System.out.printf("Found 1 in arr[%d]\n", index);
}
index = insertSearch(arr, 0, arr.length - 1, 1);
if (index == -1) {
System.out.println("1 is not found");
} else {
System.out.printf("Found 1 in arr[%d]\n", index);
}
}
//二分查找
//只能查找有序数组,每次以数组中间的数为基础,如果查找值比中间值小,向左递归;如果查找值比中间值大,向右递归
public static int binarySearch(int[] arr, int left, int right, int value) {
if (left > right) {
return -1;
}
int mid = (left + right) / 2;
int midVal = arr[mid];
if (value > midVal) {
return binarySearch(arr, mid + 1, right, value);
} else if (value < midVal) {
return binarySearch(arr, left, mid - 1, value);
} else {
return mid;
}
}
//二分查找的非递归实现
public static int binarysearchNoRecursion(int[] arr, int value) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == value) {
return mid;
} else if (arr[mid] > value) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
//插值查找,是对二分查找的一种优化, 参照数不是中间数,而是自适应的, 减少查找的次数
//当数据量较大,数据分布比较均匀时,采用插值查找,速度较快
public static int insertSearch(int[] arr, int left, int right, int value) {
if (left > right || value > arr[arr.length - 1] || value < arr[0]) {
return -1;
}
int mid = left + (right - left) * (value - arr[left]) / (arr[right] - arr[left]);
int midVal = arr[mid];
if (value > midVal) {
return insertSearch(arr, mid + 1, right, value);
} else if (value < midVal) {
return insertSearch(arr, left, mid - 1, value);
} else {
return mid;
}
}
}
07-26
07-26