C语言 找出一组数中三个最小值
时间: 2025-02-19 20:30:51 浏览: 20
C语言实现找到数组中三个最小值
在处理此类问题时,可以采用遍历数组并维护一个包含三个最小元素的列表的方式。为了确保算法效率较高,在每次遇到更小的数值时更新这三个位置中的最大者[^1]。
下面是一个具体的解决方案:
方法概述
创建一个长度为3的辅助数组用于存储当前发现的最小三个数,并初始化这些值为极大值。接着逐一遍历输入数据集内的每一个成员;如果该成员小于已知的最大值,则替换之,并重新排列这三者的顺序以保持升序状态。
示例代码
#include <stdio.h>
#include <limits.h>
void findThreeSmallest(int arr[], int n, int result[]) {
// 初始化结果数组为最大整数值
for (int i = 0; i < 3; ++i) {
result[i] = INT_MAX;
}
// 遍历给定数组来查找前三个最小值
for (int j = 0; j < n; ++j) {
if (arr[j] < result[0]) {
result[2] = result[1];
result[1] = result[0];
result[0] = arr[j];
} else if (arr[j] < result[1]) {
result[2] = result[1];
result[1] = arr[j];
} else if (arr[j] < result[2]) {
result[2] = arr[j];
}
}
}
// 测试函数
int main() {
int numbers[] = {7, 10, 4, 3, 20, 15};
int size = sizeof(numbers)/sizeof(numbers[0]);
int smallest_three[3];
findThreeSmallest(numbers, size, smallest_three);
printf("The three smallest elements are %d, %d and %d\n",
smallest_three[0], smallest_three[1], smallest_three[2]);
return 0;
}
此程序定义了一个findThreeSmallest()
函数用来接收待处理的数据序列以及返回最小子集合的结果向量。通过比较和交换操作实现了对原始列表的一次线性扫描即可完成任务的要求[^1]。
相关推荐

















