一次性找出数组中的最小值和次小值
代码:
#include <stdio.h>
int main()
{int arr[] = {5, 4, 6, 3, 9, 12, 35, 42, 18, 29, 30};int min = arr[0], submin = arr[0];for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++){if (arr[i] < min){submin = min;min = arr[i];}else if (arr[i] < submin){submin = arr[i];}}printf("min = %d, submin = %d\n", min, submin);return 0;
}
执行结果:
min = 3, submin = 4
数组中允许有两个相等的最小值。
例如:
#include <stdio.h>
int main()
{int arr[] = {5, 3, 6, 3, 9, 12, 35, 42, 18, 29, 30};int min = arr[0], submin = arr[0];for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++){if (arr[i] < min){submin = min;min = arr[i];}else if (arr[i] < submin){submin = arr[i];}}printf("min = %d, submin = %d\n", min, submin);return 0;
}
执行结果:
min = 3, submin = 3