调试一个二分查找的例子
2005-08-03 15:45
218 查看
#include "stdafx.h"
#include <vector>
#include <iostream>
int bsearch(std::vector<int> vec , int x)
{
int low ,high ;
low = 0 ;
high = vec.size() -1 ;
int mid =0 ;
while(low <=high)
{
mid = (low +high ) /2;
//if find x then break
if(vec[mid] == x) break;
//if x is greater than the mid value , assign the mid+1 to low
else if (x > vec[mid])
low = mid +1 ;
else
high = mid -1;
}
if(low <= high)
return mid;
else
return -1;
}
int main(int argc, char* argv[])
{
std::vector<int> vec ;
for(int i=0 ;i< 10;i++)
{
vec.push_back(i);
}
int ret = 0;
ret = bsearch(vec ,5);
std::cout<<"is 5 in vector "<< (ret== -1? "true":"false")<<"postion index:"<<ret <<std::endl;
ret = bsearch(vec ,11);
std::cout<<"is 11 in vector "<<(ret== -1? "true":"false")<<" position index:"<<ret <<std::endl;
return 0;
}
说明:程序使用了vector 存储数组,主要是方便取到数组长度
#include <vector>
#include <iostream>
int bsearch(std::vector<int> vec , int x)
{
int low ,high ;
low = 0 ;
high = vec.size() -1 ;
int mid =0 ;
while(low <=high)
{
mid = (low +high ) /2;
//if find x then break
if(vec[mid] == x) break;
//if x is greater than the mid value , assign the mid+1 to low
else if (x > vec[mid])
low = mid +1 ;
else
high = mid -1;
}
if(low <= high)
return mid;
else
return -1;
}
int main(int argc, char* argv[])
{
std::vector<int> vec ;
for(int i=0 ;i< 10;i++)
{
vec.push_back(i);
}
int ret = 0;
ret = bsearch(vec ,5);
std::cout<<"is 5 in vector "<< (ret== -1? "true":"false")<<"postion index:"<<ret <<std::endl;
ret = bsearch(vec ,11);
std::cout<<"is 11 in vector "<<(ret== -1? "true":"false")<<" position index:"<<ret <<std::endl;
return 0;
}
说明:程序使用了vector 存储数组,主要是方便取到数组长度
相关文章推荐
- QT小例子 ---文件查找
- 写给初学者:一个调试、利用msdn的经典例子
- 看文档还是看源代码+调试--附带rsyslog的例子
- iOS软件调试初探(一个破解app的例子)
- 如何将android例子程序添加到Eclipse进行调试运行
- Windows调试——使用windbg查找内存泄露
- 调试精通hibernate第二章例子的问题
- linux c 小程序 gdb调试命令 例子
- opencv查找轮廓---cvFindContours && cvDrawCountours 用法及例子
- 分组查找ACCESS数据库,每组随机取N条记录的例子
- 用折半查找法在一组排好序(递增有序或递减有序)的值中查找某个数据+ 冒泡排序+选择排序+数组排序(例子)
- 用emacs进行批量查找替换的例子
- selenium 元素查找find_element_by_id方法例子
- 来来来 写一个二分查找 315. Count of Smaller Numbers After Self
- 《gpu高性能运算之CUDA》matrixAssign例子调试
- VS_2005_创建DLL工程,并进行调用与调试例子
- 用 GDB 调试程序(一)---简单例子
- fmod小例子 调试通过
- C++ 字符串查找例子.
- Windows API 实现查找、删除任意类型的文件_VERSION20120612(vc6.0调试通过)(2012.6.12最新修改)