#include <stdio.h>
#include <stdlib.h>
void generateRandomNumbers(int arr[], int n) {
for (int i = 0; i < n; i++) {
arr[ i] = rand() % 100;
}
}
void displayArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[ i]);
}
printf("\n");
}
void findAboveAverage(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[ i];
}
double average = (double)sum / n;
printf("高于平均数的数据:");
for (int i = 0; i < n; i++) {
if (arr[ i] > average) {
printf("%d ", arr[ i]);
}
}
printf("\n");
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void swapMinMax(int arr[], int n) {
int minIndex = 0;
int maxIndex = 0;
for (int i = 1; i < n; i++) {
if (arr[ i] < arr[minIndex]) {
minIndex = i;
}
if (arr[ i] > arr[maxIndex]) {
maxIndex = i;
}
}
swap(&arr[minIndex], &arr[maxIndex]);
}
void reverseArray(int arr[], int n) {
int start = 0;
int end = n - 1;
while (start < end) {
swap(&arr[start], &arr[end]);
start++;
end--;
}
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[ i] == key) {
return i;
}
}
return -1;
}
int binarySearch(int arr[], int n, int key) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) {
return mid;
}
else if (arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return -1;
}
int main() {
int N;
printf("请输入数组的大小N:");
scanf("%d", &N);
int arr[N];
int n;
printf("请输入实际处理元素的个数n:");
scanf("%d", &n);
generateRandomNumbers(arr, n);
printf("随机生成的数组:");
displayArray(arr, n);
findAboveAverage(arr, n);
swapMinMax(arr, n);
printf("交换最大数和最小数的位置后的数组:");
displayArray(arr, n);
reverseArray(arr, n);
printf("逆置后的数组:");
displayArray(arr, n);
bubbleSort(arr, n);
printf("排序后的数组:");
displayArray(arr, n);
int key;
printf("请输入要查找的数:");
scanf("%d", &key);
int index = sequentialSearch(arr, n, key);
if (index != -1) {
printf("顺序查找:找到了,下标为%d\n", index);
}
else {
printf("顺序查找:未找到\n");
}
index = binarySearch(arr, n, key);
if (index != -1) {
printf("二分查找:找到了,下标为%d\n", index);
}
else {
printf("二分查找:未找到\n");
}
return 0;
}