`
_jia_shun
  • 浏览: 24918 次
  • 性别: Icon_minigender_1
  • 来自: 安徽
社区版块
存档分类
最新评论

C++大学基础教程_7_7采用线性查找法查找数组

 
阅读更多
//_7_7_main.cpp
//线性查找法用一个关键值与数组中的每一个值比较

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;

void linearSearch_1(const int [],int ,int);//线性查找函数
int linearSearch_2(const int [],int ,int);

int main()
{
	const int arraySize = 100;
	 int a[arraySize];
	srand((unsigned)time(NULL));
	for(int i=0;i<arraySize;i++)
		a[i] = rand()%11 ;//产生0到10之间的数
	cout << "要查找的数组为:" << endl;
	for(int j=0;j<arraySize;j++)
	{	cout << setw(3) << a[j] ;
		if((j+1)%10 == 0)
			cout << endl;
	}
	cout << endl;
	int element = rand()%22;//保证查找到的可能性为50%
	cout << "search key is " << element << endl;
	int m = linearSearch_2(a,element,arraySize);
	if(m!=-1)
		linearSearch_1(a,element,arraySize);
	else 
		cout << "Value no found" << endl;

	system("pause >> cout");
	return 0;
}

void linearSearch_1(const int array[],int key,int sizeOfArray)
{
	for(int i=0;i<sizeOfArray;i++)
		if(array[i] == key)
		{
			cout << "第" << i+1 << "个数与" << key 
                                << "相同" << endl;
		}
}
int linearSearch_2(const int array[],int key,int sizeOfArray)
{
	for(int i=0;i<sizeOfArray;i++)
		if(array[i] == key)
			return i;
	return -1;
}

 先判断是否有一样的元素,再进一步写出结果

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics