Skip to content

Instantly share code, notes, and snippets.

@freakflames29
Created May 5, 2021 06:53
Show Gist options
  • Save freakflames29/c8e613d9ead7c62cfc40fc8eab42eb98 to your computer and use it in GitHub Desktop.
Save freakflames29/c8e613d9ead7c62cfc40fc8eab42eb98 to your computer and use it in GitHub Desktop.
merge sort in cpp
#include <iostream>
using namespace std;
void ms(int *arr,int low,int mid,int high)
{
int b[low+high];
int i=low;
int j=mid+1;
int k=low;
while(i<=mid && j<=high)
{
if (arr[i]<arr[j])
{
b[k]=arr[i];
i++;
}
else
{
b[k]=arr[j];
j++;
}
k++;
}
while(i<=mid)
{
b[k]=arr[i];
i++;
k++;
}
while(j<=high)
{
b[k]=arr[j];
j++;
k++;
}
int p=low;
while(p<k)
{
arr[p]=b[p];
p++;
}
}
void divide(int *arr,int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
divide(arr,low,mid);
divide(arr,mid+1,high);
ms(arr,low,mid,high);
}
}
int main()
{
int arr[]={5,6,8,9,1};
divide(arr,0,5);
for (int i = 0; i < 5; ++i)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment