请用c++写一个合并函数,把两个升序排列的数组合并为一个升序数组。用随机数生成两个不等长有序数组测试合并函数。请用数组和vector类实现
时间: 2024-05-02 13:21:38 浏览: 115
使用数组实现:
```c
#include <stdio.h>
void merge(int arr1[], int n1, int arr2[], int n2, int merged[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < n1) {
merged[k++] = arr1[i++];
}
while (j < n2) {
merged[k++] = arr2[j++];
}
}
int main() {
int arr1[] = {1, 3, 5, 7, 9};
int arr2[] = {2, 4, 6, 8};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
int merged[n1 + n2];
merge(arr1, n1, arr2, n2, merged);
for (int i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}
```
使用vector类实现:
```c
#include <stdio.h>
#include <vector>
void merge(std::vector<int>& vec1, std::vector<int>& vec2, std::vector<int>& merged) {
int i = 0, j = 0;
while (i < vec1.size() && j < vec2.size()) {
if (vec1[i] <= vec2[j]) {
merged.push_back(vec1[i++]);
} else {
merged.push_back(vec2[j++]);
}
}
while (i < vec1.size()) {
merged.push_back(vec1[i++]);
}
while (j < vec2.size()) {
merged.push_back(vec2[j++]);
}
}
int main() {
std::vector<int> vec1 = {1, 3, 5, 7, 9};
std::vector<int> vec2 = {2, 4, 6, 8};
std::vector<int> merged;
merge(vec1, vec2, merged);
for (int i = 0; i < merged.size(); i++) {
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}
```
以上代码都是合并两个已经升序排列的数组,如果要合并多个数组,可以先将多个数组合并成两个数组,再使用以上代码合并两个数组。
阅读全文