折半查找又叫二分查找,它的前提是线性表中的记录必须是关键码有序(通常是从小到大有序),线性表必须采用顺序存储。
package org.example.demo;
/**
* 折半查找,也叫二分查找,时间复杂度O(logn)
*/
public class BinarySearchTest {
public static int search(int[] arr, int key) {
if (arr == null || arr.length == 0)
return -1;
int low = 0, high = arr.length - 1, mid = high + low >>> 1, e;
while ((e = arr[mid]) != key) {
if (e > key)
high = mid -1;
else
low = mid + 1;
if (low > high)
return -1;
mid = high + low >>> 1;
}
return mid;
}
private static void testCase() {
int[] arr = { 1, 2, 5, 8, 9, 11, 12, 13};
int key = 1;
System.out.println("index: " + search(arr, key));
}
private static void testCase1() {
int[] arr = null;
int key = 80;
System.out.println("index: " + search(arr, key));
}
private static void testCase2() {
int[] arr = {};
int key = 80;
System.out.println("index: " + search(arr, key));
}
public static void main(String[] args) {
testCase();
testCase1();
testCase2();
}
}