随机输入两个有序整数序列,利用合并算法,输出合并后的整数有序序列。 c++
时间: 2024-10-09 07:14:37 浏览: 55
在C++中,我们可以使用归并排序的思想来合并两个有序整数序列。以下是简单的步骤:
1. 定义一个函数,如`mergeSortedArrays`,接受两个整数指针`arr1`, `arr2`以及它们各自的长度`n1`和`n2`作为参数。
2. 创建一个新的数组`result`,用于存储合并后的有序序列。如果`n1`和`n2`都大于0,我们需要这个数组。
3. 初始化两个指针`i`和`j`分别指向`arr1`和`arr2`的开始位置。
4. 比较`arr1[i]`和`arr2[j]`,选择较小的那个元素添加到`result`并相应地移动指针。如果`arr1[i]`小于`arr2[j]`,将`arr1[i++]`添加到`result`,反之亦然。
5. 当其中一个数组遍历完之后,将另一个未遍历完的数组剩余部分直接复制到`result`的剩余空间。
6. 最后返回合并后的`result`数组。
下面是一个简化的C++代码示例:
```cpp
#include <vector>
std::vector<int> mergeSortedArrays(const std::vector<int>& arr1, const std::vector<int>& arr2) {
int n1 = arr1.size(), n2 = arr2.size();
std::vector<int> result(max(n1, n2));
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
// 如果其中一个数组还有剩余,直接复制
while (i < n1) {
result[k++] = arr1[i++];
}
while (j < n2) {
result[k++] = arr2[j++];
}
return result;
}
```
阅读全文
相关推荐


















