递归与分治策略之二分搜索算法

来源:互联网 发布:铃声剪辑软件 编辑:程序博客网 时间:2024/05/16 15:28

二分搜索算法是运用分治策略的典型例子

二分搜索算法充分利用了元素之间的次序关系(二分搜索的算法是基于有序列)采用分治策略,可在最坏情况下用O(logn)时间完成搜索任务。

二分搜索算法的基本思想是将n个元素分成个数大致相同的两半,去a[n/2]与x作比较。如果x = a[n/2],则找到x,算法终止;如果x < a[n/2],则只在数组a的左半部继续搜索;如果x > a[n/2],则只在数组a的右半部继续搜索。具体算法可描述如下:

template<class T>int BinarySearch(T a[], const T &x, int n){int lef = 0;int rig = n-1;while(lef <= rig){int mid = (lef + rig) >> 1;if(x == a[mid])return mid;if(x > a[mid])lef = mid + 1;elserig = mid - 1;}return -1;}


 

如果用递归的细想来实现,具体算法可描述如下:

template <class T>int BinarySearch(T a[], const T &x, int lef, int rig){if(lef <= rig){int mid = (lef + rig) >> 1;if(x == a[mid])return mid;else if(x > a[mid])return BinarySearch(a, x, mid+1, rig);elsereturn BinarySearch(a, x, lef, mid-1);}}


 

以上是二分搜索技术的两种实现方法。

原创粉丝点击