-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.cpp
More file actions
72 lines (60 loc) · 1.04 KB
/
mergeSort.cpp
File metadata and controls
72 lines (60 loc) · 1.04 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
#include <bits/stdc++.h>
using namespace std;
const int M = (int)10e7;
int n;
int arr2[M];
void merge(int arr[], int left,int mid,int right){
int i = left;
int j = mid+1;
int k = left;
while(i<=mid && j<=right){
if(arr[i]>arr[j]){
arr2[k] = arr[j];
j++;
}
else { arr2[k] = arr[i];
i++;
}
k++;
}
if(j>right){
while(i<=mid){
arr2[k] = arr[i];
i++;
k++;
}
}
else{
while(j<=right){
arr2[k] = arr[j];
k++;
j++;
}
}
for(int i= left; i<=right; i++){
arr[i] = arr2[i];
}
}
void printArray(){
for(int i=0; i<n; i++){
cout<<arr2[i]<<" ";
}
}
void mergeSort(int a[],int l,int r){
if(l<r){
int mid = (l+r)/2;
mergeSort(a,l,mid);
mergeSort(a,mid+1,r);
merge(a,l,mid,r);
}
}
int main() {
//freopen("input.txt","r",stdin);
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
mergeSort(arr,0,n-1);
printArray();
}