-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_sort.cpp
More file actions
64 lines (60 loc) · 1.12 KB
/
Merge_sort.cpp
File metadata and controls
64 lines (60 loc) · 1.12 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
#include <bits/stdc++.h>
using namespace std;
//T - O(nlogn)
vector<int> a;
void merge(int l, int mid, int r){
int i = l;
int j = mid + 1;
int k = 0;
vector<int> b(r-l+1);
while(i <= mid && j <= r){
if(a[i] < a[j]){
b[k] = a[i];
i++;
k++;
}
else{
b[k] = a[j];
j++;
k++;
}
}
while(i <= mid){
b[k] = a[i];
i++;
k++;
}
while(j <= r){
b[k] = a[j];
j++;
k++;
}
for(i = l; i <= r; i++){
a[i] = b[i-l];
}
}
void mergeSort(int l, int r){
if(l < r){
int mid = l + (r-l)/2;
mergeSort(l, mid);
mergeSort(mid+1, r);
merge(l, mid, r);
}
}
int main(){
int n;
cout<<"Enter size of array:"<<endl;
cin>>n;
cout<<"Enter elements of array:"<<endl;
for(int i = 0; i < n; i++){
int k;
cin>>k;
a.push_back(k);
}
mergeSort(0, n-1);
cout<<"Sorted array is :\n";
for(int i = 0; i < n; i++){
cout<<a[i]<<" ";
}
return 0;
}