Skip to content

Commit

Permalink
Create Merge Sort in C++
Browse files Browse the repository at this point in the history
  • Loading branch information
AyushiChakrabarty authored Sep 1, 2020
1 parent 4de38e6 commit 809fc11
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions Merge Sort in C++
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
//Merge sort in C++
#include<iostream>
using namespace std;

void Merge(int *A, int *L, int lc,int *R,int rc)
{
int i=0;
int j=0;
int k=0;

while(i<lc && j< rc)
{
if(L[i] < R[j])
A[k++] = L[i++];
else
A[k++] = R[j++];
}
while(i < lc)
A[k++] = L[i++];
while(j < rc)
A[k++] = R[j++];
}

// Sort an array of integers.
void MergeSort(int *A,int n)
{
int i,mid, *L, *R;
if(n < 2)
return;

mid = n/2;

L= new int[mid];
R= new int[n-mid];

for(i = 0;i<mid;i++)
L[i] = A[i];
for(i = mid;i<n;i++)
R[i-mid] = A[i];

MergeSort(L,mid);
MergeSort(R,n-mid);
Merge(A,L,mid,R,n-mid);
free(L);
free(R);
}

//Main function
int main()
{
int A[20],n;
cout<<"Enter the size of the array you want to enter:"<<endl;
cin>>n;
cout<<"Enter the array elements:"<<endl;

for(int i=0; i<n; i++)
cin>>A[i];

MergeSort(A,n);

for(int i = 0;i <n; i++)
cout<<A[i]<<" ";
return 0;
}

0 comments on commit 809fc11

Please sign in to comment.