常用查找算法

来源:互联网 发布:dell 5470 网络驱动 编辑:程序博客网 时间:2024/04/30 15:46

1. 顺序查找算法

顺序查找其实就是蛮力法,从头到尾的扫描要查找的数据,虽然时间复杂度比较高。但是也算是一种常用的算法。直接上代码吧,Java实现的。

<span style="white-space:pre"></span>/** * 普通的查找算法 *  * @param array *   查找的数组 * @param x *   查找的元素 * @return *   返回元素在数组中的位置,没找到返回-1 */public static int commonSearch(int[] array, int x) {int pos = -1;for (int i = 0; i < array.length; i++) {if (array[i] == x) {pos = i;break;}}return pos;}

 此算法的时间复杂度为O(n)


2. 折半查找算法

  折半查找相比顺序查找算法高级一点,这个算法成立的一个基本假设是:查找序列是有序的,序列必须是升序或者降序的。如果不满足这个条件,必须先对序列进行排序,让序列有序才能使用折半查找算法进行查找。折半查找的基本思想是利用中点作为分界点,若要查找的元素x比中点对应的值都大(假设查找算法),那么元素x肯定是从中点之后才开始查找。因为中点之前的值都比中点值要小。Java代码实现如下:
<span style="white-space:pre"></span>/** * 折半查找 *  * @param array *     查找的数组(查找的范围) * @param low *     查找的起点 * @param high *     查找的终点 * @param x *     查找的元素 * @return *     返回元素在数组中的位置 */public static int binarySearch(int array[], int low, int high, int x) {int pos = -1;int mid;while (low < high) {mid = (low + high) / 2;if (array[mid] == x) {return mid;} else if (array[mid] > x) {high = mid - 1;} else {low = mid + 1;}}return pos;}
此算法的时间复杂度为O(log2N)

0 0