目录
1.实验要求
建立一个一维数组a,完成以下任务,输入输出格式参见下图。
(1) 利用rand()函数产生10个10~100之间的整数,存入数组a中并输出;
(2) 使用冒泡排序法,将数组a中的数据按降序排列,并输出;
(3) 使用折半查找法在数组a中查找是否有键盘输入的指定数据,并输出查找结论(没找到或在第X个位置找到)。
2.实验思路
- 掌握冒泡排序的基本原理和实现方法;
- 掌握折半查找的基本原理和实现方法;
- 理解使用随机数生成器生成随机数组的方法;
- 掌握如何使用函数进行代码模块化设计;
- 了解时间函数time和随机数函数rand的使用方法。
3.实验代码
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// 冒泡排序
void bubbleSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j] < a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
}
// 折半查找
int binarySearch(int a[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (a[mid] == target) {
return mid;
} else if (a[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
srand(time(NULL)); // 以当前时间为随机数生成器的种子
int a[10];
for (int i = 0; i < 10; i++) {
a[i] = rand() % 91 + 10;
cout << a[i] << " ";
}
cout << endl;
bubbleSort(a, 10);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
cout << endl;
int target;
cout << "请输入要查找的数据:";
cin >> target;
int pos = binarySearch(a, 10, target);
if (pos == -1) {
cout << "没有找到" << endl;
} else {
cout << "在第" << pos + 1 << "个位置找到了" << endl;
}
return 0;
}
4.实验结果
45 64 31 33 89 32 14 42 42 70
89 70 64 45 42 42 33 32 31 14
请输入要查找的数据:42
在第5个位置找到了
5.实验总结
本段代码实现了冒泡排序和折半查找的功能。
首先,通过srand(time(NULL))函数将当前时间作为随机数生成器的种子,使用rand()%91+10随机生成了一个长度为10的数组a,并打印输出。
然后,调用bubbleSort函数对数组a进行冒泡排序,使得数组a从大到小有序排列,并打印输出排序后的数组a。
最后,要求用户输入想要查找的数据target,调用binarySearch函数在有序数组a中进行折半查找,找到目标数据后打印输出位置信息。如果没有找到,则打印输出“没有找到”。