1、定义数组,存储N个整型数据(N为40) 2、输入实际处理元素的个数n(n<=N) 3、产生n个随机数(随机数小于100)存入数组并显示。 4、完成如下功能:(通过调用上述函数实现) (1)求出所有高于平均数的数据。 (2)交换最大数和最小数的位置。 (3)对这组数据进行逆置。 (4)对这组数据进行排序(递增)并显示。 (5)算法效率分析: 从键盘输入一个数,查找数组中是否存在,并显示其下标。 对排序前(无序)数据采用顺序查找,显示依次比较的数据、比较次数以及查找结果。 对排序后数据采用二分查找,显示依次比较的数据、比较次数以及查找结果。
时间: 2024-02-03 09:11:29 浏览: 82
以下是一个实现上述要求的C++代码:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
const int N = 40;
void generateRandomArray(int a[], int n) {
srand(time(NULL));
for (int i = 0; i < n; i++) {
a[i] = rand() % 100;
}
}
void printArray(int a[], int n) {
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
double getAverage(int a[], int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
return sum / n;
}
void printAboveAverage(int a[], int n) {
double avg = getAverage(a, n);
cout << "Above average: ";
for (int i = 0; i < n; i++) {
if (a[i] > avg) {
cout << a[i] << " ";
}
}
cout << endl;
}
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
void swapMinMax(int a[], int n) {
int minIndex = 0;
int maxIndex = 0;
for (int i = 1; i < n; i++) {
if (a[i] < a[minIndex]) {
minIndex = i;
}
if (a[i] > a[maxIndex]) {
maxIndex = i;
}
}
swap(a[minIndex], a[maxIndex]);
}
void reverse(int a[], int n) {
for (int i = 0; i < n / 2; i++) {
swap(a[i], a[n - i - 1]);
}
}
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 sequentialSearch(int a[], int n, int target, int& count) {
for (int i = 0; i < n; i++) {
count++;
if (a[i] == target) {
return i;
}
}
return -1;
}
int binarySearch(int a[], int n, int target, int& count) {
int left = 0;
int right = n - 1;
while (left <= right) {
count++;
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;
}
void printSearchResult(int index, int count) {
if (index != -1) {
cout << "Found at index " << index << endl;
} else {
cout << "Not found" << endl;
}
cout << "Number of comparisons: " << count << endl;
}
int main() {
int a[N];
generateRandomArray(a, N);
int n;
cout << "Enter number of elements to process (max " << N << "): ";
cin >> n;
cout << "Original array: ";
printArray(a, n);
printAboveAverage(a, n);
swapMinMax(a, n);
cout << "After swapping min and max: ";
printArray(a, n);
reverse(a, n);
cout << "After reversing: ";
printArray(a, n);
bubbleSort(a, n);
cout << "After sorting: ";
printArray(a, n);
int target;
cout << "Enter a number to search: ";
cin >> target;
int count = 0;
int index = sequentialSearch(a, n, target, count);
cout << "Sequential search result:" << endl;
printSearchResult(index, count);
count = 0;
index = binarySearch(a, n, target, count);
cout << "Binary search result:" << endl;
printSearchResult(index, count);
return 0;
}
```
注意,这只是一个实现,可能并不是最优的实现。在实际应用中,我们需要根据数据规模和实际需求选择更合适的算法和数据结构,以达到更好的效率。
阅读全文