C语言查找数组中最大的三个数字 - 冒泡排序实现
以下是一个使用冒泡排序算法来找到一个整数数组中的最大的三个数字的 C语言示例程序。
#include <stdio.h>
void bubble_sort(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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 3, 8, 1, 6, 9, 2};
int n = sizeof(arr) / sizeof(int);
bubble_sort(arr, n);
printf('The largest three numbers in the array are: %d, %d, %d\n', arr[0], arr[1], arr[2]);
return 0;
}
输出:
The largest three numbers in the array are: 9, 8, 6
在这个程序中,我们首先定义了一个 bubble_sort 函数,使用冒泡排序算法将数组中的元素按降序排列。然后在 main 函数中调用这个函数,并打印出数组中的前三个元素即可。
原文地址: https://www.cveoy.top/t/topic/ov5a 著作权归作者所有。请勿转载和采集!