How to Write Merge Sort in C
#include<stdio.h>
/// Merge Sort
void merge(int arr[],int l,int m,int r);
void merge_sort(int arr[],int l,int r);
void print_arr(int arr[],int size);
void merge_sort(int arr[],int l,int r){
if(l<r){
int m=(l+r)/2;
merge_sort(arr,l,m);
merge_sort(arr,m+1,r);
merge(arr,l,m,r);
}
}
void merge(int arr[],int l,int m,int r){
int i,j,k;
int n1=m-l+1;
int n2=r-m;
int L[n1];
int R[n2];
for(int i=0;i<n1;i++){
L[i]=arr[l+i];
}
for(int j=0;j<n2;j++){
R[j]=arr[m+1+j];
}
i=0;
j=0;
k=l;
while(i<n1 && j<n2){
if(L[i]<=R[j]){
arr[k]=L[i];
i++;
}
else{
arr[k]=R[j];
j++;
}
k++;
}
while(i<n1){
arr[k]=L[i];
i++;
k++;
}
while(j<n2){
arr[k]=R[j];
j++;
k++;
}
}
void print_arr(int arr[],int size){
for(int i=0;i<size;i++){
printf("%d ",arr[i]);
}
printf("\n");
}
int main(){
int arr[]={11,9,7,2,5,15};
int size_arr=sizeof(arr)/sizeof(arr[0]);
printf("Before Array: ");
print_arr(arr,size_arr);
merge_sort(arr,0,size_arr-1);
printf("After Sorted Array; ");
print_arr(arr,size_arr);
return 0;
}
Comments
Post a Comment