C Program to sort an array using Merge Sort
Program
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 10
void merge_sort(int, int);
void merge(int, int, int);
int array[MAX_SIZE];
void main()
{
int i, n;
printf("Enter the number of elements:\n");
scanf("%d", &n);
printf("Enter %d elements for Sorting:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
merge_sort(0, n - 1);
printf("Sorted Data:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", array[i]);
}
}
void merge_sort(int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
merge_sort(low, mid);
merge_sort(mid + 1, high);
merge(low, mid, high);
}
}
void merge(int low, int mid, int high)
{
int temp[50];
int i = low, j = mid + 1, k = 0;
while (i <= mid && j <= high)
{
if (array[i] < array[j])
temp[k++] = array[i++];
else
temp[k++] = array[j++];
}
while (i <= mid)
temp[k++] = array[i++];
while (j <= high)
temp[k++] = array[j++];
for (i = low, j = 0; i <= high; i++, j++)
array[i] = temp[j];
}
Output
$ gcc merge-sort.c
$ ./a.out
Enter the number of elements:
6
Enter 6 elements for Sorting:
48
-9
378
-123
84
102
Sorted Data:
-123
-9
48
84
102
378