设计一个算法找出数值a[1..n]中相差最小的两个元素,要求写出算法伪代码和C/C++描述
时间: 2024-10-05 19:03:19 浏览: 34
设计一个查找数组中相差最小的两个数的算法通常涉及到遍历和比较的过程。这里提供一种简单的线性时间复杂度的解决方案:
**算法伪代码**:
```
1. 初始化两个变量 min_diff = a[0] - a[1], min_pair = (a[0], a[1])
2. 对于 i = 2 到 n-1 (数组下标从2开始到倒数第二个元素)
a. 计算当前元素与 min_pair[0] 的差值 diff = a[i] - min_pair[0]
b. 如果 diff < abs(min_diff) 或者 diff == 0 且 |diff| < |min_diff|,更新 min_diff = diff,min_pair = (a[i], min_pair[0])
c. 同理计算 a[i] - min_pair[1],如果更小则更新 min_pair
3. 返回 min_pair
```
**C/C++ 描述**:
```cpp
#include <algorithm>
#include <cmath>
pair<int, int> find_min_diff(int arr[], int n) {
if (n < 2) return make_pair(arr[0], arr[1]); // 防止数组为空
int min_diff = std::abs(arr[0] - arr[1]);
pair<int, int> min_pair = {arr[0], arr[1]};
for (int i = 2; i < n; ++i) {
int diff = std::abs(arr[i] - min_pair.first);
if (diff < min_diff || (diff == 0 && diff < min_diff)) {
min_diff = diff;
min_pair = {arr[i], min_pair.first};
}
diff = std::abs(arr[i] - min_pair.second);
if (diff < min_diff) {
min_pair.second = arr[i];
}
}
return min_pair;
}
```
阅读全文