用C++写一段用于合并两个有序数组的代码
时间: 2024-04-16 12:29:03 浏览: 156
以下是使用C++编写的合并两个有序数组的代码例:
```cpp
#include <iostream>
<vector>
std::vector<int> mergeSortedArrays(const std::vector<int>& arr1, const std::vector<int>& arr2) {
std::vector<int> mergedArray;
int i = 0; // Pointer for the first array
int j = 0; // Pointer for the second array
// Compare elements of both arrays and insert them into the new array in sorted order
while (i < arr1.size() && j < arr2.size()) {
if (arr1[i] <= arr2[j]) {
mergedArray.push_back(arr1[i]);
i++;
} else {
mergedArray.push_back(arr2[j]);
j++;
}
}
// Insert the remaining elements from the first array
while (i < arr1.size()) {
mergedArray.push_back(arr1[i]);
i++;
}
// Insert the remaining elements from the second array
while (j < arr2.size()) {
mergedArray.push_back(arr2[j]);
j++;
}
return mergedArray;
}
int main() {
// Example usage
std::vector<int> arr1 {1, 3, 5, 7};
std::vector<int> arr2 {2, 4, 6, 8};
std::vector<int> mergedArr = mergeSortedArrays(arr1, arr2);
// Output the merged array
for (int i = 0; i < mergedArr.size(); i++) {
std::cout << mergedArr[i] << " ";
}
return 0;
}
```
在主函数中,我们创建了两个已排序的数组`arr1`和`arr2`,并调用`mergeSortedArrays`函数将它们合并到`mergedArr`中。最后,我们使用循环遍历`mergedArr`并输出合并后的数组元素。运行该程序将输出合并后的有序数组:1 2 3 4 5 6 7 8。
阅读全文