Created
May 5, 2021 06:53
-
-
Save freakflames29/c8e613d9ead7c62cfc40fc8eab42eb98 to your computer and use it in GitHub Desktop.
merge sort in cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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