Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Merge sort Algorithm #38

Merged
merged 2 commits into from
Oct 1, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Added Merge sort Algorithm
  • Loading branch information
Dinesh0602 committed Oct 1, 2021
commit 63e1b94b0181fad7bf17390e07be64cc53b2515d
53 changes: 53 additions & 0 deletions Sorting/Merge sort/Mergesort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include<bits/stdc++.h>
using namespace std;
#define int long long
//used for 64 bit integers
void merge(int a[],int l, int mid,int r){
int i=l,j=mid+1,k=0;
int c[r-l+1];
while(i<=mid && j<=r){
if(a[i]<=a[j]){
c[k++]=a[i++];
}
else{
c[k++]=a[j++];
}
}
while(i<=mid){
c[k++]=a[i++];
}
while(j<=r){
c[k++]=a[j++];
}
j=l;
for(int i=0;i<r-l+1;i++){
a[j++]=c[i];
}
}

void mergesort(int a[],int l,int r){
if(l<r){
int mid=l+(r-l)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
merge(a,l,mid,r);
}
}

//main function should always be a 32 bit one so we use int32_t
int32_t main(){
int n;
cin >> n;
//size of the array
int a[n];
//declaring an array of size n
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
mergesort(a,0,n-1);
for (int i = 0; i < n; i++)
{
cout << a[i]<<" ";
}
}