查找算法---二分查找
二分查找
二分查找的思想:利用已排序的数组,每次都对半的减少查找的数量,直到找到对应的数据,时间复杂度为O(logn),比较适用于数据量适中的,因为局限于已排序的,所以对于无序的都需要进行一次排序操作。
// 递归版本 private int binarySearch2(int[] arr,int result){ return binarySearch2(arr,0,arr.length - 1,result); } private int binarySearch2(int[] arr, int low, int high, int result) { if (low > high) return -1; //使用位运算 int mid = low + ((high - low) >> 1); if (arr[mid] == result){ return result; }else if (arr[mid] > result){ return binarySearch2(arr,low,mid - 1,result); }else{ return binarySearch2(arr,mid + 1,high,result); } } // 非递归版本 private int binarySearch(int[] arr,int result){ if (arr.length == 0) { return -1; } Arrays.sort(arr); int low = 0; int high = arr.length - 1; while (low <= high){ // 不建议使用这样 建议使用 low + ((high - low) >> 1) int mid = (low + high) / 2; if (arr[mid] > result){ high = mid - 1; }else if (arr[mid] < result){ low = mid + 1; }else{ return mid; } } return -1; }
二分查找变形题
/** * 找到第一个出现的数字 * @param sortArr * @param num * @return */ private int findFirstNum(int[] sortArr,int num){ int low = 0; int high = sortArr.length - 1; while (low <= high){ int mid = low + ((high - low) >> 1); if (sortArr[mid] > num ){ high = mid + 1; }else if (sortArr[mid] < num){ low = mid - 1; }else{ // 找到对应的 但是此时不确定是不是最先出现的 if (mid == 0 || sortArr[mid - 1] != num){ return mid; }else{ high = mid - 1; } } } return -1; } /** * 查找最后一个 * @param arr * @param num * @return */ private int findLastNum(int[] arr,int num){ int low = 0; int high = arr.length - 1; while (low <= high){ int mid = low + ((high - low) >> 1); if (arr[mid] > num ){ high = mid + 1; }else if (arr[mid] < num){ low = mid - 1; }else{ // 找到对应的 但是此时不确定是不是最先出现的 if (mid == arr.length - 1 || arr[mid + 1] != num){ return mid; }else{ low = mid + 1; } } } return -1; } private int findFirstBigOne(int[] arr,int num){ int low = 0; int high = arr.length - 1; while (low <= high){ int mid = low + ((high - low) >> 1); if (arr[mid] >= num){ if (mid == 0 || arr[mid - 1] < num){ return mid; }else{ high = mid - 1; } } else{ low = mid + 1; } } return -1; } private int findLastSmallOne(int[] arr,int num){ int low = 0; int high = arr.length - 1; while (low <= high){ int mid = low + ((high - low) >> 1); if (arr[mid] < num){ high = mid - 1; } else{ if (mid == arr.length - 1 || arr[mid + 1] > num){ return mid; }else{ low = mid + 1; } } } return -1; }