-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathmergesort.cpp
76 lines (58 loc) · 1.09 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
#include<iostream>
using namespace std;
void merge(int array1[],int size1,int array2[],int size2,int *output){
int i=0,j=0,k=0;
while(i<size1 && j<size2){
if(array1[i]<array2[j]){
output[k]=array1[i];
i++;
k++;
}
else{
output[k]=array2[j];
j++;
k++;
}
}
while(i<size1){
output[k]=array1[i];
i++;
k++;
}
while(j<size2){
output[k]=array2[j];
j++;
k++;
}
}
void mergeSort(int *input,int size){
if(size<=1){
return;
}
int mid=size/2;
int size1=mid,size2=size-mid;
int array1[500],array2[500];
for(int i=0;i<mid;i++){
array1[i]=input[i];
}
int k=0;
for(int i=mid;i<size;i++){
array2[k]=input[i];
k++;
}
mergeSort(array1,size1);
mergeSort(array2,size2);
merge(array1,size1,array2,size2,input);
}
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]<<" ";
}
}