Skip to content
Home » C Programs » Merge Sort in C Program With Output

Merge Sort in C Program With Output

Merge sort in c program with output. By merging the elements in c, his merge sort program sorts the elements. Values will be initialized in the program after the completion of the value, which is how the merge sort works. This is how merge sort works in its most basic form.

Definition of While Loop

A while loop in C programming executes a target statement repeatedly as long as a condition is true. While loops are control flow statements in most computer programming languages that allow code to be executed repeatedly based on a given Boolean condition. The while loop is a loop that repeats itself, comparable to an if statement.

Increment Operator in C

In the C programming language, the increment (++) and decrement (–) operators are special unary operators. With these operators, the value of a variable is increased or decreased by one. The increment and decrement operators can only be used with variables.  

The increment operator raises the value by one, while the decrement operator lowers it by one.  With pre-increment I, the value is increased by one before being allocated to the variable. The post-increment (i++) method is used to increase the value of a variable after it has been assigned a value.

Definition of Temporary Variable in C

In computer programming, a temporary variable is a variable with a short lifetime that is used to store data that will be removed immediately or before it can be saved in a more permanent memory location. Because it’s short-lived, it’s usually referred to as a local variable or a variable with local scope.

Merge Sort in C Program With Output

#include<stdio.h>
void sort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void sort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
sort(a,i,mid); 
sort(a,mid+1,j);
merge(a,i,mid,mid+1,j); 
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; 
int i,j,k;
i=i1;
j=i2; 
k=0;
while(i<=j1 && j<=j2) 
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) 
temp[k++]=a[i++];
while(j<=j2)
temp[k++]=a[j++];
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

Output:

Enter no of elements:3
Enter array elements:345 56 78
Sorted array is :56 78 345