forked from vedant781999/Array_operation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge sort.cpp
More file actions
91 lines (88 loc) · 1.42 KB
/
Merge sort.cpp
File metadata and controls
91 lines (88 loc) · 1.42 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
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<iostream>
using namespace std;
void merge(int A[],int B[],int lb,int mid,int ub)
{
int i=lb;
int j=mid+1;
int k=0;
while(i<=mid && j<=ub)
{
if(A[i]<=A[j])
{
B[k]=A[i];
i++;k++;
}
else
{
B[k]=A[j];
j++;k++;
}
}
if(i>mid)
{
while(j<=ub)
{
B[k]=A[j];
j++;k++;
}
}
else
{
while(i<=mid)
{
B[k]=A[i];
i++;k++;
}
}
for(int k=0;k<ub-lb+1;k++)
A[k+lb]=B[k];
}
void mergesort(int A[],int B[],int lb,int ub)
{
if(lb<ub)
{
int mid = (lb+ub)/2;
mergesort(A,B,lb,mid);
mergesort(A,B,mid+1,ub);
merge(A,B,lb,mid,ub);
}
}
int main()
{ int n,i,j,lb,ub,k,mid;
cout<<"Enter the size of array"<<"\n";
cin>>n;
int A[n],B[n];
cout<<"Enter the elements of array"<<"\n";
for(int t=0;t<n;t++)
cin>>A[t];
mergesort(A,B,0,n-1);
//mergesort(A,B,mid+1,n-1);
//merge(A,B,lb,mid,ub);
for(int k=0;k<n;k++)
cout<<B[k]<<" ";
return 0;
}
int main()
{ int n,i,j,lb,ub,k,mid;
cout<<"Enter the size of array"<<"\n";
cin>>n;
int A[n],B[n];
cout<<"Enter the elements of array"<<"\n";
for(int t=0;t<n;t++)
cin>>A[t];
mergesort(A,B,0,n-1);
//mergesort(A,B,mid+1,n-1);
//merge(A,B,lb,mid,ub);
for(int k=0;k<n;k++)
cout<<B[k]<<" ";
return 0;
void mergesort(int A[],int B[],int lb,int ub)
{
if(lb<ub)
{
int mid = (lb+ub)/2;
mergesort(A,B,lb,mid);
mergesort(A,B,mid+1,ub);
merge(A,B,lb,mid,ub);
}
} }