-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path2_merge_sorted_arr.cpp
More file actions
98 lines (82 loc) · 1.46 KB
/
Copy path2_merge_sorted_arr.cpp
File metadata and controls
98 lines (82 loc) · 1.46 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
Problem statement : Given two sorted arrays, print all the elements of both the arrays in sorted order
sample ip & op
ip:
a[] = {10, 15, 20}
b[] = {5, 6, 6, 15}
op: 5 6 6 10 15 15 20
ip:
a[] = {1, 1, 2}
b[] = {3}
op: 1 1 2 3
idea: traverse both the arrays simultaneously, use two index variable i and j for accesiing array a and b
we compare a[i] and b[j]
case 1 : a[i] <= b[j]
print a[i]
i++
case 2 : a[i] > b[j]
print b[j]
j++
if (i<=n || j<=m)
print remaining elements
dry run:
a[] = {10, 20, 35}
b[] = {5, 50, 50}
i=0, j=0 => a[i]>b[j]
op: 5
i=0, j=1 => a[i]<b[j]
op: 5 10
i=1, j=1 => a[i]<b[j]
op: 5 10 20
i=2, j=1 => a[i]<b[j]
op: 5 10 20 35
print remaning el of b
op: 5 10 20 35 50 50
Time complexity: θ(n+m)
*/
#include <iostream>
using namespace std;
void mergeSortedArrays(int a[], int b[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(a[i] <= b[j])
{
cout << a[i] << " ";
++i;
}
else
{
cout << b[i] << " ";
++j;
}
}
while(i<m)
{
cout << a[i] << " ";
++i;
}
while(j<m)
{
cout << b[j] << " ";
++j;
}
}
int main()
{
int sz1, sz2;
cin >> sz1 >> sz2;
int a[sz1], b[sz2];
for (int i = 0; i < sz1; i++)
cin >> a[i];
for (int i = 0; i < sz2; i++)
cin >> b[i];
mergeSortedArrays(a, b, sz1, sz2);
}
/*
3
3
10, 20, 35
5, 50, 50
*/