Chinaunix首页 | 论坛 | 博客
  • 博客访问: 88233
  • 博文数量: 34
  • 博客积分: 2000
  • 博客等级: 大尉
  • 技术积分: 395
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-23 10:22
文章分类

全部博文(34)

文章存档

2011年(1)

2010年(4)

2009年(29)

我的朋友

分类: C/C++

2009-05-10 22:39:46

#include "stdafx.h"
#include
#include
#include
using namespace std;
/*************************************************
*折半搜索算法:复杂度O(logn),要求数据项有序排列
*顺序搜索算法:复杂度O(n),对数据项排列次序无特殊要求
*************************************************/
int binarySearch(vector ivec,const int& item)
{
 int first=0;
 int last=ivec.size ()-1;
 int mid;
 bool found=false;
 while(first<=last && !found)
 {
  mid=(first+last)/2;
  if(ivec[mid]==item)
   found=true;
  else
   if(ivec[mid]>item)
    last=mid-1;
   else
    first=mid+1;
 }
 if(found)
  return mid;
 else
  return -1;
}
int main()
{
 //折半搜索算法测试
 vector ivec;
 for(int i=0;i<16;i++)
  ivec.push_back (i+1);
 for(vector::iterator iter=ivec.begin ();
  iter!=ivec.end ();++iter)
  cout<<*iter<<" ";
 cout<
 int index=binarySearch(ivec,5);
 cout<<"The index of element 5 is:"<
 return 0;
}
阅读(463) | 评论(0) | 转发(0) |
0

上一篇:队列的数组和链式实现

下一篇:散列技术

给主人留下些什么吧!~~