-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
78 lines (60 loc) · 1.3 KB
/
MergeSort.cpp
File metadata and controls
78 lines (60 loc) · 1.3 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
73
74
75
76
77
78
#include<bits/stdc++.h>
using namespace std;
void Merge(int a[],int left,int right){
int mid = (left+right)/2;
int i = left;
int j = mid+1;
int k = left;
int temp[100];
while(i<=mid && j<=right){
if(a[i] < a[j]){
temp[k++] = a[i++];
}
else{
temp[k++] = a[j++];
}
}
while(i<=mid){
temp[k++] = a[i++];
}
while(j<=right){
temp[k++] = a[j++];
}
//We need to copy all element to original arrays
for(int i=left;i<=right;i++){
a[i] = temp[i];
}
}
void mergeSort(int a[],int left,int right){
//Base case - 1 or 0 elements
if(left>=right){
return;
}
//Follow 3 steps
//1. Divide
int mid = (left+right)/2;
//Recursively the arrays - s,mid and mid+1,e
mergeSort(a,left,mid);
mergeSort(a,mid+1,right);
//Merge the two parts
Merge(a,left,right);
}
int main(){
int a[100];
int n;
freopen("in.txt","r",stdin);
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<"Inputed Array : "<<endl;
for(int i=0;i<n;i++){
cout<<a[i]<<" , ";
}
mergeSort(a,0,n);
cout<<endl;
cout<<"Sorted Array : "<<endl;
for(int i=0;i<n;i++){
cout<<a[i]<<" , ";
}
}