0% found this document useful (0 votes)
5 views1 page

C Merge Sort Algorithm Example

The document contains a C program that implements the merge sort algorithm. It defines functions for merging sorted subarrays and recursively sorting an array. The main function handles user input for the number of elements and the elements themselves, then outputs the sorted array.

Uploaded by

berserrk98
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

C Merge Sort Algorithm Example

The document contains a C program that implements the merge sort algorithm. It defines functions for merging sorted subarrays and recursively sorting an array. The main function handles user input for the number of elements and the elements themselves, then outputs the sorted array.

Uploaded by

berserrk98
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

h>

int a[50], temp[50];

void merge(int low, int mid, int high) {


int i = low, j = mid + 1, k = low;
while(i <= mid && j <= high)
temp[k++] = (a[i] < a[j]) ? a[i++] : a[j++];
while(i <= mid) temp[k++] = a[i++];
while(j <= high) temp[k++] = a[j++];
for(i = low; i <= high; i++) a[i] = temp[i];
}

void mergesort(int low, int high) {


if(low < high) {
int mid = (low + high) / 2;
mergesort(low, mid);
mergesort(mid + 1, high);
merge(low, mid, high);
}
}

int main() {
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) scanf("%d", &a[i]);

mergesort(0, n - 1);

printf("Sorted array:\n");
for(i = 0; i < n; i++) printf("%d ", a[i]);
return 0;
}

You might also like