基于数组的折半查找

 1 //折半查找的迭代实现

 2 int BinarySearch(int *a, const int x, const int n)  3 {  4     int left=0;  5     int right = n-1;  6     while(left<=right)  7  {  8         int middle = (left+right)/2;  9         if(x<a[middle]) 10             right=middle-1; 11         else if(x>a[middle]) 12             left = middle+1; 13         else

14             return middle; 15  } 16     return -1; 17 }

 

 1 //折半查找的递归实现

 2 int BinaryFind(int *a, const int x, const int left, const int right)  3 {  4     if(left<=right)  5  {  6         int middle = (left+right)/2;  7         if(x<a[middle])  8             return BinaryFind(a,x,left,middle-1);  9         else if(x>a[middle]) 10             return BinaryFind(a,x,middle+1,right); 11         else

12             return middle; 13  } 14     return -1; 15 }

 

你可能感兴趣的:(数组)