Repository navigation
Expand file tree
/
Copy pathmerge_sort.cpp
More file actions
78 lines (66 loc) · 1.53 KB
/
Copy pathmerge_sort.cpp
File metadata and controls
78 lines (66 loc) · 1.53 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
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int> &arr, int low, int mid, int high)
{
vector<int> temp;
// starting index of left and right part
int left = low;
int right = mid + 1;
// comparing elements from both parts and adding smaller one
while (left <= mid && right <= high)
{
if (arr[left] <= arr[right])
{
temp.push_back(arr[left]);
left++;
}
else
{
temp.push_back(arr[right]);
right++;
}
}
// if any elements are left in the left part
while (left <= mid)
{
temp.push_back(arr[left]);
left++;
}
// if any elements are left in the right part
while (right <= high)
{
temp.push_back(arr[right]);
right++;
}
// putting the sorted elements back in the original array
for (int i = low; i <= high; i++)
{
arr[i] = temp[i - low];
}
}
void ms(vector<int> &arr, int low, int high)
{
// stop when only one element is left
if (low == high)
return;
int mid = (low + high) / 2;
// divide the array into two parts
ms(arr, low, mid);
ms(arr, mid + 1, high);
// merge both sorted parts
merge(arr, low, mid, high);
}
int main()
{
vector<int> mergi = {5, 3, 4, 1, 2};
int n = mergi.size();
// sorting the complete array
ms(mergi, 0, n - 1);
// printing the sorted array
for (int i = 0; i < n; i++)
{
cout << mergi[i] << " ";
}
return 0;
}