转载请注明出处:http://blog.csdn.net/ns_code/article/details/33747953
本篇博文没太多要说的,二分查找很简单,也是常见常考的查找算法,以下是递归非递归的实现。
非递归实现:
/* 非递归实现,返回对应的序号 */ int BinarySearch(int *arr,int len,int key) { if(arr==NULL || len<1) return -1; int low = 0; int high = len-1; while(low <= high) { int mid = (low+high)>>1; if(key == arr[mid]) return mid; else if(key < arr[mid]) high = mid-1; else low = mid+1; } return -1; }
递归实现:
/* 递归实现,返回对应的序号 */ int BSearch(int *arr,int low,int high,int key) { if(arr==NULL || low>high) return -1; int mid = (low+high)>>1; if(arr[mid] == key) return mid; else if(arr[mid] > key) return BSearch(arr,low,mid-1,key); else return BSearch(arr,mid+1,high,key); } /* 将递归实现的方法封装起来 */ int BinSearch(int *arr,int len,int key) { return BSearch(arr,0,len-1,key); }
【算法拾遗】二分查找递归非递归实现,布布扣,bubuko.com
时间: 2024-11-23 14:26:47