ITPub博客

首页 > 应用开发 > IT综合 > 常用查找算法 (转)

常用查找算法 (转)

原创 IT综合 作者:gugu99 时间:2007-08-17 11:28:42 0 删除 编辑
常用查找算法 (转)[@more@]

//search.h包含了所有的常用查找算法

//使用顺序查找法的查找函数
//seqSearch(const int arr[],int first,int last,int target)
template
int seqSearch(const T arr[],int first,int last,const T& target)
{
 int i=first;

 //扫描下标范围first<=i //或下标超出范围
 while (!(i==last)&&!(arr[i]==target))
 i++;

 return i;  //i是匹配值的下标,或者,如果没有匹配,则i=last
}

//模板函数find_last_of()的实现
template
int find_last_of(const T arr[],int first,int last,const T& target)
{
 int i=last-1;

 //描扫下标范围first<=i //或下标超出范围
 while(i>=first&&target!=arr[i])
 i--;
 if (i return i;
}

//二分查找算法函数binSearch()的实现
template
int binSearch(const T arr[],int first,int last,const T& target)
{
 int mid;  //中间点的下标
 T midValue;  //用于保存arr[mid]元素值

 int origLast=last;  //保存last的初始值

 while(first {
 mid=(first+last)/2;
 midValue=arr[mid];
 if (target==midValue)  //有一个匹配
 return mid;
 //确定要查找哪个子表
 else if(target last=mid;
 else
 first=mid+1;  //查找子表的后半部分,重新设置first
 }
 return origLast;  //没有找到目标值
}


 


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10748419/viewspace-963768/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: TPC_C简介 2 (转)
请登录后发表评论 登录
全部评论
  • 博文量
    3121
  • 访问量
    2644429