二分查找&插值查找
/** * 二分查找 */ public class BinarySearch{ /** * 搜索 * @param key 关键字 * @param arr 数据源 * @return int */ public static int search(int key, int[] arr) { int start = 1; int end = arr.length; //关键词越界 if (arr[start] < key || arr[end-1] < key) return -1; int mid; while(start <= end) { mid = (start + end) / 2; if (key < arr[mid]) { end = mid - 1; } else if (key > arr[mid]) { start = mid + 1; } else { return mid; } } return -1; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 9, 200}; int key = 201; int result = search(key, arr); System.out.println("search key "+key+" in offset "+result); } }
/** * 插值查找 */ public class InsertValue { /** * 搜索 * @param key 参数 * @param arr 数据源 * @return int */ public static int search(int key, int[] arr) { int start = 1; int end = arr.length-1; int mid = -1; if (key < arr[0] || key > arr[end-1]) return mid; while(start <= end) { mid = start + (end - start) * (key - arr[start]) / (arr[end] - arr[start]); if (key > arr[mid]) { start = mid + 1; } else if (key < arr[mid]) { end = mid - 1; } else { break; } } return mid; } public static void main(String[] args) { int key = 14; int[] arr = {13,14,15,55,66,89}; int result = search(key, arr); System.out.println("search key "+key+" in offset "+ result); } }