静态表,在折半查找前,一般要对其进行排序,这样才能折半。如果是顺序查找是不要求的。
1、单向冒泡排序:静态查找表在升序排序时,用到冒泡排序。在冒泡排序时每一循环都使得最后的数据时稳定的,也就是说第一次最大的数据在最后,第二次次大的数据在倒数第二,这样在每次循环时只从j=0到j
for(int i=0;i
{
for(int j=0;j
{
if(ST[j].key>ST[j+1].key)
{
t=ST[j].key;
ST[j].key=ST[j+1].key;
ST[j+1].key=t;
}
}
}
2、折半查找:递归查找和非递归查找
2.1)递归:
template
int SSearch::BiSearch_2(T key)
{
int k;
k=BiSearch2(0,len-1,key);
return k;
}
template
int SSearch::BiSearch2(int x, int y,T key) //recursive to find the key InBtween x an y,inlcude x and y
{
int mid=(x+y)/2;
if(ST[mid].key==key)
return mid;
if(x>y)
return -1;
if(key< ST[mid].key)
return BiSearch2(x,mid-1,key);
else
return BiSearch2(mid+1,y,key);
}
2.2)非递归:用到三个标志,low,high,mid.
template
int SSearch::BiSearch_1(T key) //折半查找
{
if(len==0&&ST==NULL)
{
cout<<"The Sort Table doesn't exit, plz CREAT it first!/n";
return -1;
}
else
{
int low=0,high=len-1;
int mid;
while(low<=high)
{
mid=(high+low)/2;
if(ST[mid].key==key)
{
cout<<"Find! Locate at :"<<<"/n";
return mid;
}
if(ST[mid].key>key)
high=mid-1;
else
low=mid+1;
}
cout<<"CANNOT FIND/n";
return -1;
}
}