开发中常见的算法汇总之-顺序查找

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cpongo4/article/details/89333889
#### 顺序查找 - 核心思想 - 将目标数据与源数据数组的原有顺序进行遍历比较查询,其操作基于**穷举法思想** - 特性 - 适合静态的小数据量查找,源数据量大时,查找时间复杂度会随着源数据量呈线性增长 - 对源数据中数据的顺序没有要求(有序无序都可以) - 步骤 - 对源数据数组进行遍历 - 通过目标数据和源数据集中的每一个元素进行比较查询 - 图解 006tNc79gy1g23g0ycyzhg30ra07yq8o.gif - 示例 ```java package com.lyd.algorithm.find; import com.lyd.utils.RandomUtils; import lombok.extern.slf4j.Slf4j; /** * 描述:顺序查找 *

* - 对源数据数组进行遍历 * - 通过目标数据和源数据集中的每一个元素进行比较查询 *

* * @author lyd Date 2019/4/9 ProjectName:datastructure-algo Version: 1.0 */ @Slf4j public class SequentialSearch { //查找次数即时间复杂度O(n) static int count = 0; /** * 顺序查找 * * @param source 数据源 * @param target 目标数据 * @return true存在|false不存在 */ static boolean sequentialSearch(int[] source, int target) { if (null == source || source.length < 1) { return false; } //从数组中第0个元素开始查找对比 for (int i = 0; i < source.length; i++) { count++; //找到数据后直接结束查找 if (source[i] == target) { return true; } } return false; } 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 target = RandomUtils.intArrays(1, 16)[0]; boolean result = sequentialSearch(source, target); log.info("call sequentialSearch count:{},result:{},target:{},source:{}", count, result, target, source); } } ```

猜你喜欢

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