-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.cpp
87 lines (80 loc) · 1.34 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
78
79
80
81
82
83
84
85
86
87
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
using namespace std;
int n;
void merge(int b[],int p,int c[],int q,int arr[])
{
int i=0,j=0,k=0;
while(i<p&&j<q)
{
if(b[i]<c[j])
{
arr[k]=b[i];
i++;
}
else
{
arr[k]=c[j];
j++;
}
k++;
}
if(i==p)
{
for(int x=j;x<q;x++)
{
arr[k]=c[x];
k++;
}
}else
{
for(int x=i;x<p;x++)
{
arr[k]=b[x];
k++;
}
}
if(k==n)
{
for(int x=0;x<n;x++)
{
cout<<arr[x]<<" ";
}
}
}
void mergesort(int arr[],int n)
{
int b[n],c[n];
int bn=0,cn=0;
if(n>1)
{
for(int i=0 ; i <= floor((n/2)-1);i++)
{
b[bn]=arr[i];
bn++;
}
for(int i=n/2;i<n;i++)
{
c[cn]=arr[i];
cn++;
}
mergesort(b,bn);
mergesort(c,cn);
merge(b,bn,c,cn,arr);
}
}
int main()
{
cout<<"Enter Total Elements :";
cin>>n;
int a[n];
cout<<"Enter Each Elements :\n";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Sorted Array :\n";
mergesort(a,n);
}