Merge Sort in C - Coders PlayGround

Learn to code and change the future!

Friday, 4 August 2017

Merge Sort in C

Hello Guys, here is the program for Merge Sort

#include  <stdio.h>

void mergesort(int x[],int lb,int ub);
void merge(int x[],int lb1,int ub1,int ub2);
int main()

{

 	int  i , n , x[20] ;

	printf("Enter the number of elements: ") ;

 	scanf("%d",&n) ;

 	printf("Enter the elements:\n") ;

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

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


	 mergesort(x,0,n-1) ;


 	printf("Sorted array is as shown:\n") ;

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

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

void mergesort(int x[],int lb,int ub)
{
	int mid;
	
	if(lb<ub)
	{
		mid=(lb+ub)/2;
		mergesort(x,lb,mid);
		mergesort(x,mid+1,ub);
		merge(x,lb,mid,ub);
	}
}

void merge(int x[],int lb1,int ub1,int ub2)
{
	int temp[50],i,j,k;
	
	i=lb1;
	j=ub1+1;
	k=0;

	while(i<=ub1&&j<=ub2)
	{
		if(x[i]<x[j])
			temp[k++]=x[i++];
		else
			temp[k++]=x[j++];
	}
	
	while(i<=ub1)
		temp[k++]=x[i++];

	while(j<=ub2)
		temp[k++]=x[j++];
		
	for(i=lb1,j=0;i<=ub2;i++,j++)
		x[i]=temp[j];
}

/*
OUPUT:
Enter the number of elements: 5
Enter the elements:
56
27
29
48
44
Sorted array is as shown:
27 29 44 48 56
--------------------------------
Process exited after 7.358 seconds with return value 0
Press any key to continue . . .
*/

No comments:

PropellerAds