写在前面
1、基于2021级计算机类实验指导书
2、代码仅提供参考
3、如果代码不满足你的要求,请寻求其他的途径
运行环境
window11家庭版
CLion 2023.2.2
实验要求、源代码和运行结果
1、有A和B两个数组,A数组中存储500个2000以内的随机整数,B数组中存储10个2000以内的随机整数,完成以下操作:
(1)用顺序查找算法显示B数组中每个元素在A数组中的位置,并返回该算法所用时间;
(2)用折半查找算法显示B数组中每个元素在A数组中的位置,并返回该算法所用时间;
部分参考代码如下:
#include<ctime> //使用函数库ctime …… int main() { clock_t start,finish; //定义查找开始时间和结束时间变量 …… start=clock(); //记录查找算法的开始时间 查找算法 finish=clock(); //记录查找算法的结束时间 …… }
#include <iostream>
#include <ctime>
#include <iomanip>
#include <string>
using namespace std;
// 顺序查找算法
int sequentialSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i;
}
}
return -1; // 未找到目标元素
}
// 折半查找算法(要求数组arr有序)
int binarySearch(int arr[], int n, int target) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
else if (arr[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1; // 未找到目标元素
}
int main() {
const int SIZE_A = 500;
const int SIZE_B = 10;
int A[SIZE_A];
int B[SIZE_B];
// 生成随机整数填充数组A
srand(time(NULL)); // 初始化随机种子
for (int i = 0; i < SIZE_A; i++) {
A[i] = rand() % 2000; // 生成0~1999之间的随机整数
}
// 生成随机整数填充数组B
for (int i = 0; i < SIZE_B; i++) {
B[i] = rand() % 2000; // 生成0~1999之间的随机整数
}
// 输出数组A的内容
cout << "原始数组A的内容:" << endl;
for (int i = 0; i < SIZE_A; i++) {
if (i % 10 == 0&&i!=0) {
cout << endl;
}
cout << "[" << setw(2) << i << "]" << ":" << setw(4);
cout << A[i] << " ";
}
cout << endl;
// 输出数组B的内容
cout << "数组B的内容:" << endl;
for (int i = 0; i < SIZE_B; i++) {
if (i % 10 == 0&&i!=0) {
cout << endl;
}
cout << "[" << setw(2) << i << "]" << ":" << setw(4);
cout << B[i] << " ";
}
cout << endl;
clock_t start, finish;
// 顺序查找算法
start = clock();
for (int i = 0; i < SIZE_B; i++) {
int index = sequentialSearch(A, SIZE_A, B[i]);
if (index != -1) {
cout << "B[" << i << "] 在 A 中的位置: [" << index << "]" << endl;
}
else {
cout << "B[" << i << "] 在 A 中未找到" << endl;
}
}
finish = clock();
double seqTime = double(finish - start) / CLOCKS_PER_SEC;
cout << "顺序查找算法所用时间: " << seqTime << " 秒" << endl;
// 折半查找算法(首先将A数组排序)
// 这里使用简单的冒泡排序作为示例,实际应用中可以使用更高效的排序算法
for (int i = 0; i < SIZE_A - 1; i++) {
for (int j = 0; j < SIZE_A - i - 1; j++) {
if (A[j] > A[j + 1]) {
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
// 输出排序后的数组A的内容
cout << "排序后的数组A的内容:" << endl;
for (int i = 0; i < SIZE_A; i++) {
if (i % 10 == 0&&i!=0) {
cout << endl;
}
cout << "[" << setw(2) << i << "]" << ":" << setw(4);
cout << A[i] << " ";
}
cout << endl;
start = clock();
for (int i = 0; i < SIZE_B; i++) {
int index = binarySearch(A, SIZE_A, B[i]);
if (index != -1) {
cout << "B[" << i << "] 在 A 中的位置: [" << index << "]" << endl;
}
else {
cout << "B[" << i << "] 在 A 中未找到" << endl;
}
}
finish = clock();
double binaryTime = double(finish - start) / CLOCKS_PER_SEC;
cout << "折半查找算法所用时间(包括排序时间): " << binaryTime << " 秒" << endl;
return 0;
}