C program for Merge Sort.

merge-sort.c

C program to sort the elements of the array in ascending order using Merge Sort technique is as follows:

#include<stdio.h>
#include<conio.h>

#define SIZE 6
int array_to_sort[SIZE];

void merge_sort(int left, int right);
void merge(int left, int mid, int right);

void main()
{
	int i, j, lower_bound, upper_bound;

	clrscr();

	//Get the elements of Array
	for(i=0; i<SIZE; i++)
	{
		j = i+1;
		printf("\nEnter element %d: ",j);
		scanf("%d", &array_to_sort[i]);
	}

	//Print the unsorted array.
	printf("\n\nUnsorted elements of Array are: ");
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	//Sort array.
	lower_bound = 0;
	upper_bound = SIZE-1;
	merge_sort(lower_bound, upper_bound);

	//Print the sorted array.
	printf("\n\nSorted elements of Array are: ");
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	getch();
}

//Logic for Merge Sort.
void merge_sort(int left, int right)
{
	int mid;
	if(left < right)
	{
		mid = (int)((left + right) / 2);
		merge_sort(left, mid);
		merge_sort(mid+1, right);
		merge(left, mid, right);
	}
}

void merge(int left, int mid, int right)
{
	int temp_array[SIZE];
	int i = left, j = mid + 1;
	int k = left;
	int m;

	while((i <= mid) && (j <= right))
	{
		if(array_to_sort[i] <= array_to_sort[j])
		{
			temp_array[k] = array_to_sort[i];
			i = i + 1;
			k = k + 1;
		}
		else
		{
			temp_array[k] = array_to_sort[j];
			j = j + 1;
			k = k + 1;
		}
	}
	if(i > mid)
	{
		while(j <= right)
		{
			temp_array[k] = array_to_sort[j];
			j = j + 1;
			k = k + 1;
		}
	}
	else
	{
		while(i <= mid)
		{
			temp_array[k] = array_to_sort[i];
			i = i + 1;
			k = k + 1;
		}
	}

	for(m=left; m<k; m++)
	{
		array_to_sort[m] = temp_array[m];
	}
}