//利用递归进行折半查找 //迭代的折半查找 #include <iostream> using namespace std; int BinarySearch_I(int *a, const int x, const int n); //迭代查找 指针a代表数组 int BinarySearch_R(int *a, const int x, const int left,const int right); //递归二分查找 int main() { int m[] ={1,2,3,4,5,6,7,8,9,10}; int i; int num = 7; if((i = BinarySearch_R(m,num,0,9)<0)) cout <<"没找到"<<endl; else cout <<"递归算法中:"<< "在m["<<i<<"]找到"<<num<<endl; int num1 = 9; //迭代的二分查找算法 if((i = BinarySearch_I(m,num1,10)<0)) cout <<"没找到"<<endl; else cout <<"迭代算法中:"<< "在m["<<i<<"]找到"<<num1<<endl; return 0; } int BinarySearch_I(int *a, const int x, const int n){ //迭代 int left = 0, right = n-1; while(left <= right){ int middle = (left + right)/2; if(x < a[middle]) right = middle - 1; else if(x > a[middle]) left = middle + 1; else return middle; } return -1; } int BinarySearch_R(int *a, const int x, const int left,const int right){ //递归调用 if(left <= right){ int middle = (left + right)/2; if(x < a[middle]) return BinarySearch_R(a,x,left,middle -1); //自己调用自己 else if(x> a[middle]) return BinarySearch_R(a,x,middle + 1,right); else return middle; } return -1; }
算法:递归与迭代
最新推荐文章于 2023-09-27 09:39:22 发布