Merge Sort Algorithm in C

Merge sort algorithm in c. This merge sort program is used to sort elements by merging the elements in C. How the merge sort works is values will be initialized in program after the completion of the value. This is the simple working procedure of merge sort

#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

While Loop in C Programming

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

Increment Operator to Execute Merge Sort Algorithm in C

The increment (++) and decrement (–) operators are special unary operators in C. The value of a variable is incremented or decremented by one with these operators. Only variables can be utilised with the increment and decrement operators. 

The increment operator is used to raise the value by one, whereas the decrement operator is used to decrease the value by one. The value is increased by one before being assigned to the variable with pre-increment I After assigning a value to a variable, the value is increased using the post-increment (i++) method.

Temp Variable in C

A temporary variable is a variable in computer programming that has a brief lifetime and is used to retain data that will be removed quickly or before it can be stored in a more permanent memory location. It’s commonly stated as a local variable, or a variable with local scope, because it’s short-lived.