算法-查找算法
来源:互联网 发布:切换输入法快捷键mac 编辑:程序博客网 时间:2024/05/15 13:34
查找(searching)和排序(sorting)是建立在数据结构上的重要操作。查找是指在给定信息集中查找特定信息元素的过程。本文主要讨论查找的基本概念、不同数据结构对应下的查找算法及查找效率的分析等问题。
1.查找概念
1.1 查找的定义
用关键字标识一个数据元素,查找时根据给定的某个值,在表中确定一个关键字的值等于给定值的记录或数据元素。在计算机中进行查找的方法是根据表中的记录的组织结构确定的。
1.2 查找的方法
顺序表:顺序查找、折半查找、分块查找;
树表查找;
哈希表查找;
2.顺序查找
2.1 查找目标
普通顺序表。而顺序表是指相邻两个记录的物理位置相邻的数组空间。对弈java,典型的有数组。
2.2 算法思想
设给定值为k,对顺序表L从头遍历,若到最后一个依然没有i使得L[i] == k,则返回-1;否则,返回i。
2.3 算法描述
int spsearch(int[] dist, int key){ int i = 0 int length = dist.length(); for(; i<length && dist[i] != key; i++); if(i < length){ return i; }else{ return -1; }}
2.4 算法实例
下面给出java String类的indexOf()方法的源码,该方法就是通过顺序查找实现的。
/** * Code shared by String and StringBuffer to do searches. The * source is the character array being searched, and the target * is the string being searched for. * * @param source the characters being searched. * @param sourceOffset offset of the source string. * @param sourceCount count of the source string. * @param target the characters being searched for. * @param targetOffset offset of the target string. * @param targetCount count of the target string. * @param fromIndex the index to begin searching from. */ static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { if (fromIndex >= sourceCount) { return (targetCount == 0 ? sourceCount : -1); } if (fromIndex < 0) { fromIndex = 0; } if (targetCount == 0) { return fromIndex; } char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); for (int i = sourceOffset + fromIndex; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* Found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i - sourceOffset; } } } return -1; }
2.5 算法分析
ASL= O(n);
3. 二分法查找
3.1 使用对象
有序表
3.2 算法思路
对给定值k,逐步确定待查记录所在区间,每次将搜索空间减少1/2,直到查找成功或失败为止。
3.3 算法模型
int binSearch(int[] dist, int key){ int start = 0; int end = dist.length() - 1; int mid = 0; while(start <= end){ mid = (start + end) / 2; if(dist[mid] == key) return mid; else if(key > dist[mid]) start = mid + 1; else end = mid - 1; } return -1;}
3.4 算法实例
二分法的一个典型实例是牛顿法求方程的根。
0 0
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法:
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- 查找算法
- Nginx:正向代理与反向代理的区别
- 深层学习为何要“Deep”(下)
- ubuntu14.04安装opencv
- display:inline、display:block、display:inline-block三者真实用途及含义是什么?
- “fatal: 'git status --porcelain' failed in submodule
- 算法-查找算法
- 9.Linux驱动开发前奏(2)-硬件访问技术
- Web服务器、容器、Servlet分别干什么?
- 8086汇编常见问题及解决方案
- C++ 实现tring字符串trim函数和split函数
- 一次奇妙的大项目维护经历(1)
- 大奖赛现场统分
- React 开发中的几个注意点
- J2EE的组成。