五大常用算法(一) 分治算法(1) 二分查找

本文章参考自:http://blog.163.com/wujiaxing009@126/blog/static/71988399201241481757657/

1.最基础的二分查找:

#include <iostream> using namespace std; int bsearch(int t[],int k,int n){ int low = 0; int high = n - 1; int mid; while(low <= high){//等于的情况才是最普遍的情况,不能忘记等于号 mid = (low + high) / 2; if( k == t[mid]) return mid; else if(k < t[mid]) high = mid - 1; else low = mid + 1; } return -1; } int main(){ int t[10]; for(int i = 0; i < 10; i++){ cin >> t[i]; } //sort... for(int i = 0; i < 10; i++) cout << t[i] << " "; cout << endl; int k; cin >> k; cout << bsearch(t,k,10)<<endl; return 0; }

或者写为递归的形式也可以实现二分查找。

若出现了重复的情况:则可以为:

#include <iostream> using namespace std; int bsearch(int *t,int k,int n) { int low=0,high=n-1,mid; while (low<=high) { mid=(low+high)/2; if (k==t[mid]) { while(t[mid] == k) { mid--; } return mid+1; } else if (k<t[mid]) high=mid-1; else low=mid+1; } return -1; } int main(){ int t[10]; for(int i = 0; i < 10; i++){ cin >> t[i]; } //sort... for(int i = 0; i < 10; i++) cout << t[i] << " "; cout << endl; int k; cin >> k; cout << bsearch(t,k,10)<<endl; return 0; }

为了提高效率,我们使用分治的方法改进如下:

#include <iostream> using namespace std; int bsearch(int *t,int k,int n){ int high = n - 1; int low = 0; int mid; int flag = -1; while(low <= high){ mid = (low+high) / 2; if(t[mid] == k){ flag = mid;//保存上次查找的信息 high = mid - 1;//找第一次出现k的位置,所以往左边找 } else if(k < t[mid]) high = mid - 1; else low = high + 1; } if(flag == -1) return -1; else return flag; } int main(){ int t[10]; for(int i = 0; i < 10; i++){ cin >> t[i]; } //sort... for(int i = 0; i < 10; i++) cout << t[i] << " "; cout << endl; int k; cin >> k; cout << bsearch(t,k,10)<<endl; return 0; }
    原文作者:五大常用算法
    原文地址: https://blog.csdn.net/louistech/article/details/8890711
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞