top of page
Wave
Cactus%20Plant_edited.jpg

MERGE SORT USING RECURSION

#include<stdio.h>
#include<stdlib.h>
int main()
{
    void merge_sort(int *,int ,int );
    void merge(int *,int ,int ,int );
    void display(int *,int );
    int *a,n,i;
    printf("how many values you want to insert: ");
    scanf("%d",&n);
    printf("\n");
    a=(int*)malloc(sizeof(int)*n);
    for(i=0;i<n;i++)
    {
        printf("array[%d]= ",i+1);
        scanf("%d",&a[i]);
    }
    printf("\nThe given array before merge sort:\n");
    display(a,n);
    merge_sort(a,0,n-1);
    printf("\nThe given array after merge sort:\n");
    display(a,n);
    return 1;    
}
void display(int a[],int n)
{
    int i;
    for(i=0;i<n;i++)
    printf("%d ",a[i]);
    printf("\n");  
}
void merge(int a[100],int low,int mid,int high)
{
    int b[100],i,j,h,k;
    i=low;        
    h=low;    
    k=mid+1;  
    while(h<=mid&&k<=high)
    {
        if(a[h]<=a[k])
        {
            b[i]=a[h];
            h++;
        }
        else
        {
            b[i]=a[k];
            k++;
        }
        i++;
    }
    if(h>mid)     
    {        
        for(j=k;j<=high;j++)
        {
            b[i]=a[j];
            i++;
        }
    }
    else
    {        
        for(j=h;j<=mid;j++)
        {
            b[i]=a[j];
            i++;
        }
    }    
    for(j=low;j<=high;j++)
    {
        a[j]=b[j];
    }
}
void merge_sort(int a[100],int low,int high)
{
    int mid;
    if(low<high)
    {
        mid=(low+high)/2;
        merge_sort(a,low,mid);
        merge_sort(a,mid+1,high);
        merge(a,low,mid,high);
    }    

}

Subscribe Form

Thanks for submitting!

  • Facebook
  • YouTube
  • Instagram
  • Twitter

©2020 by Abhisek Midya ( A18 )

bottom of page