设计算法求数组中相差最小的两个元素(称为最接近数)的差。要求分别给出伪代码和 C++ 描述
时间: 2023-05-14 09:05:35 浏览: 361
C语言程序设计-求一批数中最大值和最小值的差.c
5星 · 资源好评率100%
伪代码:
1. 对数组进行排序
2. 初始化最小差值为数组中相邻两个元素的差值
3. 遍历数组,计算相邻两个元素的差值,如果小于当前最小差值,则更新最小差值
4. 返回最小差值
C 代码:
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
int closest(int arr[], int n) {
qsort(arr, n, sizeof(int), cmp);
int min_diff = abs(arr[1] - arr[0]);
for (int i = 2; i < n; i++) {
int diff = abs(arr[i] - arr[i-1]);
if (diff < min_diff) {
min_diff = diff;
}
}
return min_diff;
}
int main() {
int arr[] = {3, 7, 1, 9, 4, 6, 8, 2, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int min_diff = closest(arr, n);
printf("The closest numbers have a difference of %d.\n", min_diff);
return 0;
}
阅读全文