forked from ambujraj/hacktoberfest2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMERGE.CPP
77 lines (77 loc) · 1.14 KB
/
MERGE.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.h>
#include<conio.h>
void print(int ar[],int n);
void mergeSort(int ar[],int low,int high);
void merge(int ar[],int low,int mid,int high);
void main()
{
clrscr();
int ar[20],n,i;
cout<<"Enter no. of elements."<<endl;
cin>>n;
cout<<"Enter elements"<<endl;
for(i=0;i<n;i++)
{
cin>>ar[i];
}
mergeSort(ar,0,n-1);
cout<<"Sorted elements are:"<<endl;
print(ar,n);
getch();
}
void mergeSort(int ar[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergeSort(ar,low,mid);
mergeSort(ar,mid+1,high);
merge(ar,low,mid,high);
}
}
void merge(int ar[],int low,int mid,int high)
{
int L[10],R[20],n1,n2,i,j,k;
n1=mid-low+1;
n2=high-mid;
for(i=0;i<n1;i++)
L[i]=ar[low+i];
for(j=0;j<n2;j++)
R[j]=ar[mid+j+1];
i=j=0;
k=low;
while((i<n1)&&(j<n2))
{
if(L[i]<=R[j])
{
ar[k]=L[i];
i++;
}
else
{
ar[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
ar[k]=L[i];
i++;
k++;
}
while(j<n2)
{
ar[k]=R[j];
j++;
k++;
}
}
void print(int ar[],int n)
{
for(int i=0;i<n;i++)
{
cout<<ar[i]<<endl;
}
}