-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path8_MergeSort.cpp
More file actions
48 lines (41 loc) · 824 Bytes
/
8_MergeSort.cpp
File metadata and controls
48 lines (41 loc) · 824 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
47
48
#include <bits/stdc++.h>
using namespace std;
int *aux;
void merge(int arr[], int low, int mid, int high)
{
for(int k=low; k<=high; k++){
aux[k] = arr[k];
}
int i=low, j=mid+1;
for(int k=low; k<=high; k++)
{
if(i>mid) arr[k] = aux[j++];
else if(j>high) arr[k] = aux[i++];
else if(aux[i] <= aux[j]) arr[k] = aux[i++];
else arr[k] = aux[j++];
}
}
void mergeSort(int arr[], int low, int high)
{
if(low < high)
{
int mid = low + (high - low)/2;
mergeSort(arr, low, mid);
mergeSort(arr, mid+1, high);
merge(arr, low, mid, high);
}
}
int main()
{
int n; cin >> n;
int arr[n];
aux = new int[n];
for(int i=0; i<n; i++) cin >> arr[i];
mergeSort(arr, 0, n-1);
delete []aux;
for(int i=0; i<n; i++){
cout << arr[i] << " ";
}
cout << endl;
return 0;
}