编写一个程序,用C++源代码写一个折半查找的程序

如题所述

http://www.google.com/codesearch?hl=zh-CN&q=+lang:c%2B%2B+binsearch+show:tnC-LLKnLwg:_YBEhkWZaDM:AE4NgCHv0UY&sa=N&cd=1&ct=rc&cs_p=http://wwwse.inf.tu-dresden.de/data/courses/ws05/se1/exercises/binsearch.tgz&cs_f=binsearch.cpp#first

/**
@file binsearch.cpp
@author (c) 2005 Zbigniew Jerzak (after Programming Pearls by Jon Bentley and C++ Language by Bjarne Stroustrup)

@brief Illustrates the use of assertions when using the C++ language

Assertions regarding binary search:

1. Sorted array[0..n-1]
2. We search for an element t
3. n>=0
4. array[0] <= array[1] <= ... <= array[n-1]
5. iff n==0 array is empty
6. Datatypes of t and array elements are the same
7. The return value is stored in variable p
8. iff p=-1 elemet t was not found in array[0..n-1] otherwise
9. 0 <= p <= n-1 && t=array[p]
*/

#include <sstream>
#include <iostream>

using namespace std;

#define INFO(str) str, __FILE__, __LINE__

/**
@brief Asserts using exceptions.

@returns Throws an exception X is the expression expr is not
true. No action is taken otherwise. Executes only
if the debug mode is set.
*/
template <class T, class X>
inline void Assert(T expr, X x)
{
#ifndef NDEBUG
if(!expr) throw x;
#endif //NDEBUG
}

/**
@brief the basic exception class, to be subclassed
*/
class CException
{
public:
CException(string s, char* f, int l) : _s(s), _f(f), _l(l) {};
string err() const {
ostringstream stm;
stm << _l;
return _s + " [File: " + _f + "; Line: " + stm.str() + "]";
}
private:
string _s;
string _f;
int _l;
};

/**
@brief Thrown when the precondition is violated
*/
class CPreconditionException : public CException {
public:
CPreconditionException(string s, char* f, int l) : CException(s, f, l) {};
};

/**
@brief Thrown when the invariant is violated
*/
class CInvariantException : public CException {
public:
CInvariantException(string s, char* f, int l) : CException(s, f, l) {};
};

/**
@brief Thrown when the precondition is violated
*/
class CPostconditionException : public CException {
public:
CPostconditionException(string s, char* f, int l) : CException(s, f, l) {};
};

/**
@brief retuirns the index of the element t in array

@param array - the sorted array in which to find t
@param t - the element to find
@param n - the size of the array

@return Index of the element t in the array. If not found, returns -1.
*/
template<class T>
class CBinarySearch
{
public:
//c'tor & d'tor
CBinarySearch() {}
~CBinarySearch() {}

//array manipulation
int binsearch(const T *array, const T t, const int n) const;
void initarray(T *array, const int n, const int f, const int s) const;

//assertions related
class CAssertionException : public CException {
public:
CAssertionException(string s, char* f, int l) : CException(s, f, l) {};
};

void sortedEx(const T *array, const int n) const;
int sorted(const T *array, const int n) const;
int mustbe(const int lower, const int upper, const T *array, const T t) const;
};

/**
@brief Verifies that a value t is in the range of array
*/
template <class T>
inline int CBinarySearch<T>::mustbe(const int lower, const int upper, const T *array, const T t) const
{
return(array[lower] <= t && t <= array[upper]);
}

/**
@brief returns the index of the element t in array

@param array - the sorted array in which to find t
@param t - the element to find
@param n - the size of the array

@return Index of the element t in the array. If not found, returns -1.
*/
template<class T>
inline int CBinarySearch<T>::binsearch(const T *array, const T t, const int n) const
/**
precondition:
array[0] <= array[1] <= ... <= array[n-1]

postcondition:
p == -1 => t not found in array
0 <= p <= n => array[p] == t

This constitutes a contract -- hence we call this
programming/design by contract.

DBC advocates writing the assertions first.
*/

{
const string vpre = "Violated Precondition";
const string vpst = "Violated Postcondition";
const string vinv = "Violated Invariant";

/* Make sure the search makes sense */
if(n<1 || array[0] > t || t > array[n-1])
return -1;

/* precodition 2 variants*/
#ifndef NDEBUG
sortedEx(array, n);
#endif //NDEBUG
//Assert(sorted(array, n), new CPreconditionException(INFO(vpre)));

int lower=0;
int upper=n-1;

Assert( mustbe(lower, upper, array, t), new CInvariantException(INFO(vinv)));

int middle=-1;

while (lower <= upper)
{
Assert( lower <= upper && mustbe(lower, upper, array, t), new CInvariantException(INFO(vinv)));

//Assert( middle != ((lower + upper) / 2), new CInvariantException(INFO(vinv)));
middle = (lower + upper) / 2;

Assert( lower <= middle && middle <= upper && mustbe(lower, upper, array, t), new CInvariantException(INFO(vinv)));

if(array[middle] < t)
{
Assert( mustbe(middle+1, upper, array, t), new CInvariantException(INFO(vinv)));

lower = middle;

Assert( mustbe(lower, upper, array, t), new CInvariantException(INFO(vinv)));
}
else if (array[middle] == t)
{
Assert( array[middle] == t, new CPostconditionException(INFO(vpst)));
return middle;
}
else /* array[middle] > t*/
{
Assert( mustbe(lower, middle-1, array, t), new CInvariantException(INFO(vinv)));
upper = middle - 1;
Assert( mustbe(lower, upper, array, t), new CInvariantException(INFO(vinv)));
}

Assert( mustbe(lower, upper, array, t), new CInvariantException(INFO(vinv)));
}

Assert( lower > upper && mustbe(lower, upper, array, t), new CPostconditionException(INFO(vpst)));
/* t not in array */
return -1;
}

/**
@brief Verifies whether the array is sorted

@param array - the array to verify
@param n - array size

@return 1 if array is sorted, 0 otherwise.
*/
template <class T>
inline int CBinarySearch<T>::sorted(const T *array, const int n) const
{
int i;
if(n>=2)
for(i=0; i<n-1; ++i)
if(array[i] > array[i+1])
return 0;
return 1;
}

/**
@brief Verifies whether the array is sorted

@param array - the array to verify
@param n - array size

@return Throws the CAssert whenever the array is not sorted, takes no action otherwise.
*/
template <class T>
inline void CBinarySearch<T>::sortedEx(const T *array, const int n) const
{
if(!sorted(array,n)) throw new CAssertionException(INFO("Violated Sorted Precondition"));
}

/**
@brief Initializes given array with sorted values

@param array - array to initialize
@param n - number of elements
@param f - initial element
@param s - step

@return 0 on success, 1 otherwise
*/
template <class T>
inline void CBinarySearch<T>::initarray(T *array, const int n, const int f, const int s) const
{
int i;
int elem = f;

for(i = 0; i<n; ++i)
{
array[i] = elem;
elem += s;
}
}

/**
@brief The main program body.

@returns 0 on successfull execution. 1 otherwise.
*/
int main(int argc, char **argv)
{
long array[50];
CBinarySearch<long> bs;

bs.initarray(array, 50, 5, 2);
try
{
//array[25] = 2222;
cout << bs.binsearch(array, 13, 50) << endl;
}
/* catch (CBinarySearch<long>::CAssertionException *e)
{
cout << e->err() << endl;
}
catch (CPreconditionException *e)
{
cout << e->err() << endl;
}
*/
catch (CException *e)
{
cout << e->err() << endl;
}

return 0;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2007-10-15
#include<iostream>
using namespace std;
#include<stdio.h>
#define N 10

void input(int num[],char name[N][8])
{
int i;
for(i=0;i<N;i++)
{
printf("\n Input No.:");
scanf("%d",&num[i]);
printf("Input name:");
getchar();
gets(name[i]);
}
}

void sort(int num[],char name[N][8])
{
int i,j,min,temp1;
char temp2[8];
for(i=0;i<N-1;i++)
{
min=i;
for(j=i;j<N;j++)
if(num[min]>num[j])
min=j;
temp1=num[i];
strcpy(temp2,name[i]);
num[i]=num[min];
strcpy(name[i],name[min]);
num[min]=temp1;
strcpy(name[min],temp2);
}
printf("\n result:\n");
for(i=0;i<N;i++)
printf("\n %5d%10s",num[i],name[i]);
}

void search(int n,int num[],char name[N][8])
{
int top,bott,mid,loca;
int sign=1,min;
loca=0;
top=0;
bott=N-1;
if((n<num[0])||(n>num[N-1]))
loca=-1;
while((sign==1)&&(top<=bott))
{
min=(bott+top)/2;
if(n==num[mid])
{
loca=mid;
printf("NO.%d,his name is %s.\n",n,name[loca]);
sign=-1;
}
else if (n<num[mid])
bott=mid-1;
else
top=mid+1;
}
if(sign==1||loca==-1)
printf("Can not find %d.\n",n);
}

void main()
{
int num[N],number,flag=1,c,n;
char name[N][8];
input(num,name);
sort(num,name);
while(flag==1)
{
printf("\n Input number to look for:");
scanf("%d",&number);
search(number,num,name);
printf("Contine or not(Y/N)?");
getchar();
c=getchar();
if(c=='N'||c=='n')
flag=0;
}
}

用C++语言编写折半查找算法的程序
include<iostream>#include<cstdlib>using namespace std;int binary_search(int arr[], int len, int val){int low = 0, high = len - 1, mid = 0;while (low <= high){mid = (low + high) \/ 2;if (val == arr[mid])return mid;if (val < arr[mid])low = mid + 1;else...

C++折半查找的基本思想和步骤
步骤:1、首先确定整个查找区间的中间位置 mid=( left + right) \/2 。2、用待查关键字值与中间位置的关键字值进行比较;若相等,则查找成功,若大于,则在后(右)半个区域继续进行折半查找,若小于,则在前(左)半个区域继续进行折半查找。3、对确定的缩小区域再按折半公式,重复上述步骤。最...

求一个折半插入排序的c++程序 简单点的 急 在线等
while (low <= high) { \/\/ 在arr[low..high]中折半查找有序插入的位置 int m = (low + high) \/ 2; \/\/ 折半 if (arr[0].key < arr[m].key) \/\/ 关键字相同时,使low = m + 1,到高半区,保证稳定性 high = m - 1; \/\/ 插入点在低半区 else low = m + 1; \/\/ 插...

C++折半查找法
折半查找法是算法一种,可以被任何计算机语言使用。用C语言自然也可以实现。1、定义:在计算机科学中,折半搜索(英语:half-interval search),也称二分搜索(英语:binary search)、对数搜索(英语:logarithmic search),是一种在有序数组中查找某一特定元素的搜索算法。搜索过程从数组的中间元素开始,...

如何编写C语言程序?
1.打开桌面上的DEV_C++,进入如下界面:2.快捷键“CTRL+N”建立新源代码。3.输入源代码,下面给出最简单的Hello,world源代码:include <stdio.h> int main( ){ printf("Hello,World\\n");return 0;} 4.按下F11编译并且运行源代码,得到运行结果:5.点击任意键返回源代码编辑界面可以继续进行开发...

C++:有15个数按又大到小顺序放在一个数组中,输入一个数,要求用折半法查...
折半查找法最好的就是用函数的递归调用。比如上题,要在一个15个元素的递增数组S中查找数值A,查找范围是S[0]-S[14],那么首先是找出中间点S[7]作比较,如果S[7]等于A就是找到了,如果S[7]大于A,则说明A在S[0]-S[6]之间;反之,如果S[7]小于A,则说明A在S[8]-S[14]之间,然后...

数据结构C++,有关设置监视哨的顺序查找和折半查找的问题?
按照题目要求改写的程序如下(见图)问题1 问题2

一个简单的商品管理系统程序清单 c++ 请25号前交给我 malchike@live.cn...
cout<<"结束程序, 请选择: 6 "<<endl;cin>>ch;switch (ch){ case 1:sort1(pro[N].stock,pro[N].sales);break;case 2:sort2(pro[N].code);break;case 3:{ cout<<"请输入商品代码";cin>>code;search2(code);}break;case 4:search1();break;case 5:out();break;case ...

用c++编写答案
4.这又带出个问题,当我们一个个去比较1!2!3!4!5!这样是不是非常浪费,因为在做阶乘运算也是复杂度比较高的。那么我们如何快速定位到属于哪个阶乘,显然我们降低复杂度,就是从中间开始,会有所优化,慢慢两头发展,你会发现这里又回到了大小比较上什么样的大小比较是最高效的,就是类似折半查...

求一个用c语言或c++语言编写的游戏程序,就像超级玛丽之类的游戏。
1:工欲善其事,必先利其器 这里介绍几个学习C语言必备的东东: 一个开发环境,例如turbo C 2.0,这个曾经占据了DOS时代开发程序的大半个江山。但是现在windows时代,用turbo C有感觉不方面,编辑程序起来很吃力,并且拖放,更没有函数变量自动感应功能,查询参考资料也不方便。建议使用Visual C++,这个...

相似回答