开发中常见的算法汇总之-二分查找

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cpongo4/article/details/89333891
#### 二分查找 - 核心思想 - 又称**折半查找法**,选取源数据集的中间值进行比较,每次查找将会缩小一半源数据集的数据量,基于**分治算法思想**,将大数据量不断进行分解 - 特性 - 查找的数据源必须具备有序性 - 必须基于数组结构来存储源数据集 - 可以使用递归来处理子问题 - 步骤 - 选取源数据集的中间元素 - 将源数据集按照中间元素一分为二(左边部分和右边部分) - 每次和源数据集的中间元素进行比较,小于中间元素则舍弃右边部分的数据,大于中间元素则舍弃左边部分的数据(每一次查找过后都会减少源数据中的一半数据量) - 重复上述1-3的步骤进行数据查找 - 图解 006tNc79gy1g23g4gylj0g30rh084n1b.gif - 示例 ```java package com.lyd.algorithm.find; import com.lyd.algorithm.sort.QuickSort; import com.lyd.utils.RandomUtils; import lombok.extern.slf4j.Slf4j; /** * 描述:二分查找 *

* - 选取源数据集的中间元素 * - 将源数据集按照中间元素一分为二(左边部分和右边部分) * - 每次和源数据集的中间元素进行比较,小于中间元素则舍弃右边部分的数据,大于中间元素则舍弃左边部分的数据(每一次查找过后都会减少源数据中的一半数据量) * - 重复上述1-3的步骤进行数据查找 *

* * @author lyd Date 2019/4/9 ProjectName:datastructure-algo Version: 1.0 */ @Slf4j public class BinarySearch { //查找次数即时间复杂度O(logn) static int count = 0; /** * 二分查找 * * @param source 源数据集 * @param target 目标数据 * @return true存在|false不存在 */ static boolean binarySearch(int[] source, int target) { //先排序 QuickSort.quickSort(source); //查找 return search(source, target, 0, source.length - 1); } /** * 查找 * * @param source 源数据集 * @param target 目标元素 * @param left 源数据集起始索引位置 * @param right 源数据集末尾索引位置 * @return true存在|false不存在 */ static boolean search(int[] source, int target, int left, int right) { //二分后没有找到目标元素 if (left >= right) { return false; } //查找次数(记录查找次数) count++; //起始索引位置 int le = left; //末尾索引位置 int ri = right; //计算中间值索引位置=起始索引+((末尾索引-起始索引)/2) int mid = le + ((ri - le) >> 1); //如果目标值和中间值相等则查找成功 if (target == source[mid]) { return true; } //如果目标值小于中间值则丢弃中间值右边数据 if (target < source[mid]) { //末尾索引变为中间值索引 ri = mid - 1; } //如果目标值大于中间值则丢弃中间值左边数据 if (target > source[mid]) { //起始索引变为中间值索引 le = mid + 1; } return search(source, target, le, ri - 1); } public static void main(String[] args) { // int[] source = new int[]{13, 15, 13, 5, 6, 11, 16, 20, 17, 12, 5, 6, 11, 16, 20, 17}; int[] source = RandomUtils.intArrays(512, 1000); int target = RandomUtils.intArrays(1, 1000)[0]; // int target = 16; boolean result = binarySearch(source, target); log.info("call binarySearch count:{},result:{},target:{},source:{}", count, result, target, source); } } } ```

猜你喜欢

转载自blog.csdn.net/cpongo4/article/details/89333891