數(shù)據(jù)結(jié)構(gòu)折半查找算法 折半查找算法及代碼?
折半查找算法及代碼?#include<iostream>#使用命名空間std模板<class T>int二進(jìn)制搜索(ta[],const T&x,int n,int left,i
折半查找算法及代碼?
#include<iostream>
#使用命名空間std
模板<class T>
int二進(jìn)制搜索(ta[],const T&x,int n,int left,int right)
{
if(left>=right)
return-1
else
if(a[(left right)/2]==x)
return if(left right)/2
else if(x>=(left right)/2)
returnBinarySearch(a,x,n,(left right)/21,right)
else if(x<(left right)/2)
返回BinarySearch(a,x,n,left,(left right)/2-1)
}
int main()
{
int a[MAXusize
]int i,len,x,P
CIN gt>len for(i=0I<leni)
CIN gt>A[i
]CIN gt>X
P=BinarySearch(a,x,len,0,len-1)
如果(P==-1)
cout<<“數(shù)字不存在!“<<endl
else
cout<<P 1<<endl
return 0
}
二進(jìn)制搜索算法是一種快速搜索算法。當(dāng)我們?cè)诹硪粋€(gè)數(shù)組中尋找一個(gè)數(shù)字時(shí),我們通常直接遍歷這個(gè)數(shù)組直到找到這個(gè)數(shù)字。時(shí)間復(fù)雜度為O(n)。如果有大量的數(shù)據(jù),我們可以使用簡(jiǎn)單快速的搜索算法二進(jìn)制搜索算法,也稱(chēng)為半搜索算法。