-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
46 lines (41 loc) · 716 Bytes
/
MergeSort.cpp
File metadata and controls
46 lines (41 loc) · 716 Bytes
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
#include <bits/stdc++.h>
using namespace std;
int a[20000];
int temp[20000];
int doMerge(int low, int high)
{
int mid = (low + high) / 2;
int i = 0, j = mid + 1, k = 0;
while(i <= mid && j <= high)
{
if(a[i] < a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while(i <= mid)
temp[k++] = a[i++];
while(j <= high)
temp[k++] = a[j++];
for (int x = low; x <= high; x++)
a[x] = temp[x];
}
void MSort(int low, int high)
{
if(low == high)
return;
int mid = (low + high) / 2;
MSort(low, mid);
MSort(mid + 1, high);
doMerge(low, high);
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
MSort(0, n - 1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}