//_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;
}
先判断是否有一样的元素,再进一步写出结果
本文介绍了一种简单的线性查找算法实现,并通过C++代码示例展示了如何在一个整数数组中查找特定元素。该算法适用于未排序的数据集合,通过逐个比较目标值与数组中的每个元素来确定目标是否存在。
705

被折叠的 条评论
为什么被折叠?



