参考:https://blog.csdn.net/wqc19920906/article/details/78118968
二分查找的问题:https://yq.aliyun.com/articles/3670
静态查找:
1. 顺序查找;
/**顺序查找平均时间复杂度 O(n) * @param searchKey 要查找的值 * @param array 数组(从这个数组中查找) * @return 查找结果(数组的下标位置) */ public static int orderSearch(int target, int[] arr) { if(arr == null || arr.length < 1) return -1; for(int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; } } return -1; }
2. 二分查找;
private static int binarySearch(int[] arr, int key) { int low = 0; int high = arr.length - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
一般的二分查找只要求找到目标元素的位置,但是不保证该位置是否为该元素出现的第一个位置或者最后一个位置,现在想输出该元素第一次出现的位置:
public class BinarySearchFirstOne { public static void main(String[] args) { int[] arr = {1,2,3,3,3,4,5,5,6,7,7,7,8,9,9}; int target = 7; System.out.println(search(arr, target)); }
//方法代码 public static int search(int[] arr, int target) { int lo = 0; int hi = arr.length - 1; int mid; while(lo < hi) { mid = (lo + hi) >>> 1; if(arr[mid] < target) { lo = mid + 1; } else hi = mid; } if(arr[lo] == target) { return lo; } else return -1; } }
3. 分块查找