-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge Sort
More file actions
75 lines (67 loc) · 1.1 KB
/
Merge Sort
File metadata and controls
75 lines (67 loc) · 1.1 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
#include<iostream>
using namespace std;
void merge(int *a,int *b,int *c,int s,int e)
{
int m=(s+e)/2;
int i=s;
int j=m+1;
int k=s;
while(i<=m and j<=e)
{
if(b[i]<=c[j])
{
a[k++]=b[i++];
}
else
{
a[k++]=c[j++];
}
}
while(i<=m)
{
a[k++]=b[i++];
}
while(j<=e)
{
a[k++]=c[j++];
}
}
void merge_sort(int *a,int s,int e)
{
//base case
if(s>=e)
{
return;
}
//1.divide
int b[100],c[100];
int m=(s+e)/2;
for(int i=s;i<=m;i++)
{b[i]=a[i];}
for(int i=m+1;i<=e;i++)
{
c[i]=a[i];
}
//2.sort
merge_sort(b,s,m);
merge_sort(c,m+1,e);
//3.merge
merge(a,b,c,s,e);
}
int main()
{
int a[]={4,1,2,6,0,5};
int n=sizeof(a)/sizeof(int);
cout<<"before sorting"<<endl;
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}cout<<endl;
merge_sort(a,0,n-1);
cout<<"after sorting"<<endl;
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}cout<<endl;
return 0;
}