-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sorting.cpp
83 lines (78 loc) · 1.76 KB
/
merge_sorting.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
#include <bits/stdc++.h>
using namespace std;
void printArr(const vector<int> &arr)
{
for (int i = 0; i < arr.size(); ++i)
{
cout << arr[i] << " ";
}
}
vector<int> merge_sort(vector<int> arr)
{
// base case
if (arr.size() <= 1)
{
return arr;
}
int mid = arr.size() / 2;
//(left) 2 4 6 | 3 5 7 9 (right)
vector<int> left;
for (int i = 0; i < mid; i++)
{
left.push_back(arr[i]);
}
vector<int> right;
for (int i = mid; i < arr.size(); i++)
{
right.push_back(arr[i]);
}
// working with recursion
vector<int> sorted_left = merge_sort(left);
printArr(sorted_left);
cout << '\n';
vector<int> sorted_right = merge_sort(right);
printArr(sorted_right);
cout << '\n';
vector<int> sorted_array;
int indxl = 0;
int indxr = 0;
// merging sorted_left & sorted_right arry in sorted array
for (int i = 0; i < arr.size(); i++)
{
if (indxl == sorted_left.size())
{
sorted_array.push_back(sorted_right[indxr]);
indxr++;
}
else if (indxr == sorted_right.size())
{
sorted_array.push_back(sorted_left[indxl]);
indxl++;
}
else if (sorted_left[indxl] < sorted_right[indxr])
{
sorted_array.push_back(sorted_left[indxl]);
indxl++;
}
else
{
sorted_array.push_back(sorted_right[indxr]);
indxr++;
}
}
return sorted_array;
}
int main()
{
int n;
cin >> n;
vector<int> array;
for (int i = 0; i < n; i++)
{
int elements;
cin >> elements;
array.push_back(elements);
}
vector<int> ans = merge_sort(array);
printArr(ans);
}