Tue Jun 19 2018
Merge Sort
C Programming2363 views
File Name: merge-sort.c
#include<stdio.h>
void sort(int array[], int low, int high, int mid) {
int swap[10], i = low, j, l = low, m = mid + 1;
while(l <= mid && m <= high) {
if(array[l] <= array[m]) {
swap[i] = array[l];
l++;
}
else {
swap[i] = array[m];
m++;
}
i++;
}
if(l > mid) {
for(j = m; j <= high; j++) {
swap[i] = array[j];
i++;
}
}
else {
for(j = l; j <= mid; j++) {
swap[i] = array[j];
i++;
}
}
for(j = low; j <= high; j++)
array[j] = swap[j];
}
void merge(int array[], int low, int high) {
int mid;
if(low < high) {
mid = ((high - low) / 2) + low;
merge(array, low, mid);
merge(array, mid + 1, high);
sort(array, low, high, mid);
}
}
int main() {
int data[10], i;
printf("Enter 10 random number to sort in ascending order:\n");
for(i = 0; i < 10; i++)
scanf("%d", &data[i]);
/* Sorting array using call by reference */
merge(data, 0, 9);
printf("After sort\n");
for(i = 0; i < 10; i++)
printf("%d\n",data[i]);
return 0;
}
/* Output */
Enter 10 random number to sort in ascending order:
4
6
1
8
3
7
2
5
9
0
After sort
0
1
2
3
4
5
6
7
8
9
Reference:
Author:Geekboots