本文属借鉴他人之作,稍作修改:
折半查找法也称为二分查找法,采用分治策略,可以以O(log n)完成搜索任务,条件就是数组有序。
算法思想:
将n个元素分成个数大致相同的两半,取a[n/2]与欲查找的x作比较,如果x=a[n/2]则找到x,算法终止。如果x<a[n/2],则我们只要在数组a的左半部继续搜索x(这里假设数组元素呈升序排列)。如果x>a[n/2],则我们只要在数组a的右半部继续搜索x。
平时我们看到的都是迭代实现,很少有人去递归,这里给出一个递归的实现。
递归实现:
- template<classKey>
- intbinary_search(const Key*r,constint&low,constint&high,constKey&k)
- {
- intmid=(low+high)/2;
- if(low<high)
- {
- if(k<=r[mid])
- binary_search(r,low,mid,k);
- else
- binary_search(r,mid+1,high,k);
- }
- elseif(low==high)
- {
- if(k==r[mid])
- returnlow;
- else
- return-1;
- }
- else
- return-1;
- }
再给一个迭代的,也就是我们平时很经常用到的。
迭代实现:
- template<classKey>
- intbinary_search(const Key*r,constint&size,constKey&k)
- {
- intlow=0,high=size-1,mid;
- while(low<high)
- {
- mid=(low+high)/2;
- if(k>r[mid])
- low=mid+1;
- else
- high=mid;
- }
- if(low>high)
- return-1;
- else
- {
- if(k==r[low])
- returnlow;
- else
- return-1;
- }
- }