#include <stdio.h>
void merge(int a[], int start, int mid, int end);
void mergesort(int a[], int start, int end);
main() {
int a[100], i, j, n, t;
printf("Enter size of the array:");
scanf("%d", & n);
printf("Enter elements of the array");
for (i = 1; i <= n; i++)
scanf("%d", & a[i]);
mergesort(a, 1, n);
printf("\nSorted array is : ");
for (i = 1; i <= n; i++)
printf("%d ", a[i]);
}
void mergesort(int a[], int start, int end) {
int mid;
if (start < end) {
mid = (start + end) / 2;
mergesort(a, start, mid);
mergesort(a, mid + 1, end);
merge(a, start, mid, end);
}
}
void merge(int a[], int start, int mid, int end) {
int i, j, k, k1;
int t[50];
i = start;
j = mid + 1;
k = start;
while (i <= mid && j <= end) {
if (a[i] < a[j]) {
t[k] = a[i];
i++;
k++;
} else {
t[k] = a[j];
j++;
k++;
}
}
if (i > mid) {
for (k1 = j; k1 <= end; k1++) {
t[k] = a[k1];
k++;
}
} else {
for (k1 = i; k1 <= mid; k1++) {
t[k] = a[k1];
k++;
}
}
for (k1 = start; k1 <= end; k1++)
a[k1] = t[k1];
}
Note: Need to be arranged in compiler after copied
OutPut:
Enter size of the array: 5
Enter elements of the array
5
3
7
2
8
Sorted array is : 2 3 5 7 8