设计算法求数组中相差最小的两个元素的差。要求分别给出伪代码和c++描述
时间: 2024-05-18 20:18:19 浏览: 170
伪代码:
```
1. 排序数组 arr
2. 初始化最小差值为无穷大 diff = ∞
3. 遍历数组,对于每个相邻的元素 arr[i] 和 arr[i+1]
a. 计算当前差值 curr_diff = arr[i+1] - arr[i]
b. 如果 curr_diff < diff,则更新 diff = curr_diff
4. 返回最小差值 diff
```
C描述:
```c
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int findMinDifference(int arr[], int size) {
// 排序数组
qsort(arr, size, sizeof(int), compare);
int diff = INT_MAX; // 初始化最小差值为无穷大
// 遍历数组,计算最小差值
for (int i = 0; i < size - 1; i++) {
int curr_diff = arr[i + 1] - arr[i];
if (curr_diff < diff) {
diff = curr_diff;
}
}
return diff;
}
int main() {
int arr[] = {4, 9, 2, 15, 7};
int size = sizeof(arr) / sizeof(arr[0]);
int minDiff = findMinDifference(arr, size);
printf("最小差值为:%d\n", minDiff);
return 0;
}
```
该算法首先对数组进行排序,然后遍历数组找到相邻元素的差值,并更新最小差值。最后返回最小差值。
阅读全文