Sorting two arrays to one

Hello, i want to put two arrays in one and arrange it so that it is constantly increasing. The precondition is that both arrays have elements in an increasing order.
This is what I have done so far but I am a bit lost now. Hope you can help me! :)

#include<iostream>
#include<vector>
using namespace std;

vector<double> merge(const vector<double>& v1, const vector<double>& v2) {
int i = 0;
int j = 0;
int k = 0;
int n1 = v1.size();
int n2 = v2.size();
int n3 = n1 + n2;
vector<double> v3(n3);
while (j < n1) {
bool found = false;
while ((k < n2) and (not found)) {
if (v1[j] <= v2[k]) {
v3[i] = v1[j];
found = true;
++j;
}
else {
v3[i] = v2[k];
++k;
}
++i;
}
}
return v3;
}

void read_vector(vector<double>& v) {
for (int i = 0; i < v.size(); ++i) cin >> v[i];
}

void print_vector(vector<double>& v) {
for (int i = 0; i < v.size(); ++i) cout << v[i] << " ";
}

int main() {
int n1;
cin >> n1;
vector<double> v1(n1);
read_vector(v1);
int n2;
cin >> n2;
vector<double> v2(n2);
read_vector(v2);
vector<double> v3;
v3 = merge(v1, v2);
print_vector(v3);

}
edit your post please and wrap it in codetags "<>", otherwise it's difficult to make comments about certain parts of your sourcecode

in your while loop is an "and", that is "&&" in c++
and "not" is "!"
Last edited on
I solved in the end!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<vector>
using namespace std;

vector<double> merge(const vector<double>& v1, const vector<double>& v2) {
               vector<double> v3(v1.size() + v2.size());
               int i, j, k;
               i = j = k = 0;
               while (i < v1.size() && j < v2.size()) {
                     if (v1[i] <= v2[j]) {
                               v3[k] = v1[i];
                               ++i;
                     }
                     else {
                          v3[k] = v2[j];
                          ++j;
                     }
                     ++k;
               }
               while (i < v1.size()) {
                     v3[k] = v1[i];
                     ++i;
                     ++k;
               }
               while (j < v2.size()) {
                  v3[k] = v2[j];
                  ++j;
                  ++k;
               }
               return v3;
}
                                      
void read_vector(vector<double>& v) {
     for (int i = 0; i < v.size(); ++i) cin >> v[i];
}

void print_vector(vector<double>& v) {
     for (int i = 0; i < v.size(); ++i) cout << v[i] << " ";
}
               
int main() {
    int n1;
    cin >> n1;
    vector<double> v1(n1);
    read_vector(v1);
    int n2;
    cin >> n2;
    vector<double> v2(n2);
    read_vector(v2);
    vector<double> v3;
    v3 = merge(v1, v2);
    print_vector(v3);
}
Topic archived. No new replies allowed.