要求:給定已
按升序排好序的n個元素a[0:n-1],現要在這n個元素中找出一特定元素x。
分析:
- 該問題的規模縮小到一定的程度就可以容易地解決;
如果n=1即只有一個元素,則只要比較這個元素和x就可以確定x是否在表中。因此這個問題滿足分治法的第一個適用條件
- 該問題可以分解為若干個規模較小的相同問題;
- 分解出的子問題的解可以合並為原問題的解;
- 分解出的各個子問題是相互獨立的。
比較x和
a的
中間元素
a[mid],
若x=a[mid],則x在L中的位置就是mid;
如果x<a[mid],則x在a[mid]的前面;
如果x>a[mid],則x在a[mid]的后面。
無論在哪部分查找x,其方法都和在a中查找x一樣,只不過是查找的規模縮小了。這就說明此問題滿足分治法的第二個和第三個適用條件。
非遞歸算法描述:
binarysearch
low ←1;high ←n;j ←0
while (low≤high) and (j=0)
mid ←(low+high)/2
if x=A[mid] then j ←mid
else if x<A[mid] then high ←mid-1
else low ←mid+1
end while
return j
非遞歸算法C++代碼:
#include<iostream> #define MAX_SIZE 102 using namespace std; template<class Type> int BinarySearch(Type a[],const Type& x,int n) { int left=0; int right=n-1; while(left<=right) { int middle=(left+right)/2; if(a[middle]==x) return middle; if(x>=a[middle]) left=middle+1; else right=middle-1; } return -1; } int main() { int a[MAX_SIZE]; int i,len,x,p; cin>>len; for(i=0;i<len;i++) cin>>a[i]; cin>>x; p=BinarySearch(a,x,len); if(p==-1) cout<<"該數不存在!"<<endl; else cout<<p+1<<endl; return 0; }
遞歸算法描述:
If low >high then return 0
else
mid ←(low+high)/2
if x=A[mid] then return mid
else if x<A[mid] then return
binarysearch(low,mid-1)
else return binarysearch(mid+1,high)
end if
遞歸算法C++代碼:
#include<iostream> #define MAX_SIZE 102 using namespace std; template <class T> int BinarySearch(T a[],const T&x,int n,int left,int right) { if(left>=right) return -1; else { if(a[(left+right)/2]==x) return (left+right)/2; else if(x>=(left+right)/2) return BinarySearch(a,x,n,(left+right)/2+1,right); else if(x<(left+right)/2) return BinarySearch(a,x,n,left,(left+right)/2-1); } } int main() { int a[MAX_SIZE]; int i,len,x,p; cin>>len; for(i=0;i<len;i++) cin>>a[i]; cin>>x; p=BinarySearch(a,x,len,0,len-1); if(p==-1) cout<<"該數不存在!"<<endl; else cout<<p+1<<endl; return 0; }
算法復雜度分析:
每執行一次算法的while循環, 待搜索數組的大小減少1/2。
因此,在最壞情況下,while循環被執行了O(logn) 次。
循環體內運算需要O(1) 時間,因此整個算法在最壞情況下的計算時間復雜性為
O(logn)
