-
Notifications
You must be signed in to change notification settings - Fork 3
/
Merge Sort.cpp
83 lines (64 loc) · 1.23 KB
/
Merge Sort.cpp
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
#include <iostream>
using namespace std;
void mergeSort(int input[], int size){
int i=si;
int j=mid+1;
int k=0;
int arr[ei-si+1];
while(i<=mid && j<=ei){
if(input[i]>input[j]){
arr[k]=input[j];
k++;
j++;
}
else{
arr[k]=input[i];
k++;
i++;
}
}
while(i<=mid){
arr[k]=input[i];
k++;
i++;
}
while(j<=ei){
arr[k]=input[j];
k++;
j++;
}
k=0;
for(int i=si;i<=ei;++i){
input[i]=arr[k];
k++;
}
return ;
}
void mergeSort_helper(int a[], int si, int ei)
{
if(si>=ei)
{
return;
}
int mid = (si+ei)/2;
mergeSort_helper(a, si, mid);
mergeSort_helper(a, mid+1, ei);
merge(a, si,mid, ei);
return ;
}
void mergeSort(int input[], int size)
{
mergeSort_helper(input,0,size-1);
return;
}
int main() {
int length;
cin >> length;
int* input = new int[length];
for(int i=0; i < length; i++)
cin >> input[i];
mergeSort(input, length);
for(int i = 0; i < length; i++) {
cout << input[i] << " ";
}
}