来源:http://blog.csdn.net/q3498233/article/details/4419285
递归方法
1 int BinSearch(int Array[],int low,int high,int key/*???*/) 2 { 3 if (low<=high) 4 { 5 int mid = (low+high)/2; 6 if(key == Array[mid]) 7 return mid; 8 else if(key<Array[mid]) 9 return BinSearch(Array,low,mid-1,key); 10 else if(key>Array[mid]) 11 return BinSearch(Array,mid+1,high,key); 12 } 13 else 14 return -1; 15 }
非递归算法
1 int BinSearch(int Array[],int SizeOfArray,int key/*???*/) 2 { 3 int low=0,high=SizeOfArray-1; 4 int mid; 5 while (low<=high) 6 { 7 mid = (low+high)/2; 8 if(key==Array[mid]) 9 return mid; 10 if(key<Array[mid]) 11 high=mid-1; 12 if(key>Array[mid]) 13 low=mid+1; 14 } 15 return -1; 16 }
原文:http://www.cnblogs.com/huashanqingzhu/p/5163841.html