如题:
以下是顺序查找的全部代码:
#include <iostream>
#include <fstream>
using namespace std;
int SSearch(int array[], int low, int high, int target );
#define ALLNUM 1000000
int main(int argc, char *argv[])
{
if (argc != 3)
{
cout<<"参数数错误!"<<endl;
return -1;
}
ifstream inFile(argv[1]);
if(inFile.fail())
{
cout<<"文件"<<argv[1]<<"读取失败!"<<endl;
inFile.close();
return -2;
}
int numArray[ALLNUM];
int count = 0,temp;
while(inFile>>temp)
{
numArray[count++] = temp;
}
inFile.close();
inFile.clear();
inFile.open(argv[2]);
if(inFile.fail())
{
cout<<"文件"<<argv[2]<<"读取失败!"<<endl;
inFile.close();
return -2;
}
cout<<"不在large_bubble.txt中的数据:";
int cannotFind ;
while(inFile>>temp)
{
cannotFind = SSearch(numArray,0,count ,temp);
if (-1 != cannotFind)
{
cout<<cannotFind<<" ";
}
}
cout<<endl;
inFile.close();
return 0;
}
/*
*array——含有若干整数的数组,low 与 high——查找的起始、结束下标,target——待查找的元素。
*程序设定当待查元素被找到后返回-1,否则返回带找元素
*/
int SSearch(int array[], int low, int high, int target )
{
while(low < high)
{
if (array[low++] == target)
{
return -1;
}
}
return target;
}
以下是二分查找的部分代码,仅仅把上面程序的ssearch函数替换成bsearch函数:
/*
*array——含有若干整数的数组,low 与 high——查找的起始、结束下标,target——待查找的元素。
*程序设定当待查元素被找到后返回-1,否则返回带找元素
*/
int BSearch(int array[], int low, int high, int target )
{
int mid = (high + low)/2;
if (array[mid] == target)
{
return -1;
}
else if (mid != low)
{
if (array[mid] > target)
{
return BSearch(array,low,mid,target);
}
else
{
return BSearch(array,mid+1,high,target);
}
}
else return target;
}
程序运行结果如下: