计科《算法设计与分析》第三周作业——顺序查找和二分查找

如题:

以下是顺序查找的全部代码:

#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;
}


程序运行结果如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值