-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy path08 MergingFunction.cpp
92 lines (79 loc) · 1.88 KB
/
08 MergingFunction.cpp
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
#include <iostream>
using namespace std;
template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
void Merge(int x[], int y[], int z[], int m, int n){
int i = 0;
int j = 0;
int k = 0;
while (i < m && j < n){
if (x[i] < y[j]){
z[k++] = x[i++];
} else {
z[k++] = y[j++];
}
}
while (i < m){
z[k++] = x[i++];
}
while (j < n){
z[k++] = x[j++];
}
}
void MergeSingle(int A[], int low, int mid, int high){
int i = low;
int j = mid+1;
int k = low;
int B[high+1];
while (i <= mid && j <= high){
if (A[i] < A[j]){
B[k++] = A[i++];
} else {
B[k++] = A[j++];
}
}
while (i <= mid){
B[k++] = A[i++];
}
while (j <= high){
B[k++] = A[j++];
}
for (int i=low; i<=high; i++){
A[i] = B[i];
}
}
int main() {
int A[] = {2, 10, 18, 20, 23};
int m = sizeof(A)/sizeof(A[0]);
Print(A, m, "\t A");
int B[] = {4, 9, 19, 25};
int n = sizeof(B)/sizeof(B[0]);
Print(B, n, "\t B");
int r = m+n;
int C[r];
Merge(A, B, C, m, n);
// Print function does not work for variable length array C
cout << "Sorted" << ": [" << flush;
for (int i=0; i<r; i++){
cout << C[i] << flush;
if (i < r-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
cout << endl;
int D[] = {2, 5, 8, 12, 3, 6, 7, 10};
Print(D, sizeof(D)/sizeof(D[0]), "\t\tD");
MergeSingle(D, 0, 3, 7);
Print(D, sizeof(D)/sizeof(D[0]), " Sorted D");
return 0;
}