1 /* 2 递归二分查找_I 3 迭代二分查找_R 4 5 */ 6 7 8 #include "BinarySearch_I_and_R.h" 9 #include <iostream> 10 using namespace std; 11 int BinarySearch_I(int *a,int nLen,int nTarget); 12 int BinarySearch_R(int *a,int nTarget,int left,int right); 13 14 int main() 15 { 16 int nTest=7; 17 const int nLen = 10; 18 int m[nLen] = {1,2,3,4,5,6,7,8,9,10}; 19 20 int nRet = BinarySearch_I(m,nLen,nTest); 21 if (-1 == nRet) 22 { 23 cout <<"迭代二分:没找到"<<endl; 24 } 25 else 26 { 27 cout <<"迭代二分:找到了"<<endl; 28 } 29 30 31 nRet = BinarySearch_R(m,nTest,0,nLen-1); 32 if (-1 == nRet) 33 { 34 cout <<"递归二分:没找到"<<endl; 35 } 36 else 37 { 38 cout <<"递归二分:找到了"<<endl; 39 } 40 41 42 43 44 system("pause"); 45 return 0; 46 } 47 48 49 //迭代二分 50 int BinarySearch_I(int *a,int nLen,int nTarget) 51 { 52 int left = 0; 53 int right = nLen-1; 54 int mid; 55 56 while(left <= right) 57 { 58 mid = (left + right) / 2; 59 if (nTarget == a[mid]) 60 { 61 return mid; 62 } 63 else if (nTarget > a[mid]) 64 { 65 left = mid + 1; 66 } 67 else if (nTarget < a[mid]) 68 { 69 right = mid - 1; 70 } 71 72 } 73 74 return -1; 75 } 76 77 78 //递归二分 79 int BinarySearch_R(int *a,int nTarget,int left,int right) 80 { 81 82 if (left <= right) 83 { 84 int mid = (left + right)/2; 85 if (nTarget < a[mid]) 86 { 87 return BinarySearch_R(a,nTarget,left,mid-1); 88 } 89 else if (nTarget > a[mid]) 90 { 91 return BinarySearch_R(a,nTarget,mid+1,right); 92 } 93 else 94 { 95 96 return mid; 97 } 98 } 99 100 101 return -1; 102 }