Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views3 pages

Merge Sort

The document contains a C program that implements the merge sort algorithm to sort an array of integers. It prompts the user to input the size and elements of the array, displays the array before and after sorting. The program uses recursive functions to divide the array and merge the sorted subarrays back together.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views3 pages

Merge Sort

The document contains a C program that implements the merge sort algorithm to sort an array of integers. It prompts the user to input the size and elements of the array, displays the array before and after sorting. The program uses recursive functions to divide the array and merge the sorted subarrays back together.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Merge sort:

#include <stdio.h>

void mergesort(int a[],int low,int high);

void merge(int a[],int low,int mid,int high);

void main()

int a[20],n,i;
printf("Enter size of the list:");

scanf("%d",&n);

printf("enter elements:\n");

for(i=0;i<n;i++)
{

scanf("%d",&a[i]);

printf("Before sorting elements are:\n");

for(i=0;i<n;i++)

printf(" %d ",a[i]);

}
mergesort(a,0,n-1);

printf("After sorting elements are:\n");

for(i=0;i<n;i++)

printf(" %d ",a[i]);
}

void mergesort(int a[],int low,int high)

int mid;

if(low<high)

{
mid=(low+high)/2;
mergesort(a,low,mid);

mergesort(a,mid+1,high);

merge(a,low,mid,high);

void merge(int a[],int low,int mid,int high)


{

int i=low,j=mid+1,k=low,b[20],x;

while(i<=mid&&j<=high)

{
if(a[i]<a[j])

b[k]=a[i];

i=i+1;

else

b[k]=a[j];
j=j+1;

k=k+1;

if(i>mid)
{

for(x=j;x<=high;x++)

b[k]=a[x];

k=k+1;

}
else
{

for(x=i;x<=mid;x++)

b[k]=a[x];

k=k+1;

}
}

for(x=low;x<=high;x++)

a[x]=b[x];

}
Output:

Enter size of the list:10

enter elements:

12

45

74

13
2

31

8
Before sorting elements are:

5 12 45 74 13 2 31 4 9 8

After sorting elements are:

2 4 5 8 9 12 13 31 45 74

You might also like