-
Notifications
You must be signed in to change notification settings - Fork 105
/
MergeSort.cpp
77 lines (68 loc) · 1.35 KB
/
MergeSort.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
#include <iostream>
using namespace std;
void merge(int input[],int si,int ei,int mid)
{
int *output=new int[ei+1];
int i=si;
int j=mid+1;
int k=0;
while(i<=mid&&j<=ei)
{
if(input[i]<input[j])
{
output[k]=input[i];
i++;
k++;
}
else
{
output[k]=input[j];
j++;
k++;
}
}
while(j<=ei)
{
output[k]=input[j];
j++;
k++;
}
while(i<=mid)
{
output[k]=input[i];
i++;
k++;
}
int m=0;
for(int i=si;i<=ei;i++)
{
input[i]=output[m];
m++;
}
}
void mergeSort(int input[],int si,int ei)
{
if(si>=ei)
{
return;
}
int mid=(si+ei)/2;
mergeSort(input,si,mid);
mergeSort(input,mid+1,ei);
merge(input,si,ei,mid);
}
void mergeSort(int input[], int size){
// Write your code here
mergeSort(input,0,size-1);
}
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] << " ";
}
}