waiting...'s Blog
顺序查找
-
#include <iostream>
-
#include <ctime>
-
#include <cstdlib>
-
using namespace std;
-
-
// 设置随机整数的种子
-
void rand_seed()
-
{
-
unsigned int seed = static_cast<unsigned int>(time(0));
-
srand(seed);
-
}
-
-
// 返回一个介于lower与upper之间的一个随机整数
-
int randInt(int lower, int upper)
-
{
-
return lower + rand() % (upper - lower + 1);
-
}
-
-
void print(const int a[], const int length)
-
{
-
for (int i = 0; i < length; i++)
-
cout << a[i] << " ";
-
cout << endl;
-
}
-
-
// 如果待查找数字存在于数组中,则返回其下标;否则返回-1
-
int linear_search(const int a[], const int length, int num)
-
{
-
for (int i = 0; i < length; i++)
-
{
-
if (a[i] == num)
-
return i;
-
}
-
return -1;
-
}
-
-
int main()
-
{
-
const int length = 20;
-
const int lower = 1; // 随机数上限
-
const int upper = 1000; // 随机数下限
-
int a[length];
-
int num; // 待查找的数字
-
-
for (int i = 0; i < length; i++)
-
a[i] = randInt(lower, upper);
-
-
print(a, length);
-
-
cout << "请输入要查找的数字:";
-
while (cin >> num)
-
{
-
int num_index = linear_search(a, length, num);
-
if (num_index != -1)
-
cout << "a[" << num_index << "] = " << a[num_index] << endl;
-
else
-
cout << "未找到" << endl;
-
cout << "请输入要查找的数字:";
-
}
-
-
return 0;
-
}