-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sort.cpp
More file actions
104 lines (90 loc) · 2.02 KB
/
merge_sort.cpp
File metadata and controls
104 lines (90 loc) · 2.02 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
99
100
101
102
103
104
/*------------------------------------------------------
author : Aritra Chowdhury
created : Monday | 03 June,2024 | 21:47:23
------------------------------------------------------*/
#include <bits/stdc++.h>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
#define read(type) readInt<type>() // Fast read
#define ll long long
#define nL "\n"
#define pb push_back
#define mk make_pair
#define pii pair<int, int>
#define a first
#define b second
#define vi vector<int>
#define vi vector<int>
#define vll vector<long long>
#define vs vector<string>
#define all(x) (x).begin(), (x).end()
#define umap unordered_map
#define uset unordered_set
#define MOD 1000000007
#define imax INT_MAX
#define imin INT_MIN
#define exp 1e9
#define sz(x) (int((x).size()))
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
void merge(vector<int>&a, int low, int mid, int high)
{
vector<int>temp;
int left = low;
int right = mid+1;
while(left <= mid && right <= high)
{
if(a[left]<=a[right])
{
temp.push_back(a[left]);
left++;
}
else
{
temp.push_back(a[right]);
right++;
}
}
while(left <= mid)
{
temp.push_back(a[left]);
left++;
}
while(right <= high)
{
temp.push_back(a[right]);
right++;
}
for(int i=low; i<=high; i++)
{
a[i] = temp[i-low];
}
}
void mergeSort(vector<int>&a, int low, int high)
{
if(low >= high) return;
int mid = (low+high)/2;
mergeSort(a,low, mid);
mergeSort(a,mid+1,high);
merge(a,low,mid,high);
}
int main()
{
int n;
cin>>n;
vector<int>a(n);
for(int i=0; i<n; i++)
{
cin>>a[i];
}
mergeSort(a,0,n-1);
for(int i=0; i<n; i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}