5.
5.implement Merge sort algorithm for sorting a list of integers in ascending order
#include
void merge(int a[], int low, int mid, int high)
{
int i = low, j = mid + 1, k = 0;
int temp[100];
while(i <= mid && j <= high)
{
if(a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while(i <= mid)
temp[k++] = a[i++];
while(j <= high)
temp[k++] = a[j++];
for(i = low, k = 0; i <= high; i++, k++)
a[i] = temp[k];
}
void mergeSort(int a[], int low, int high)
{
int mid;
if(low < high)
{
mid = (low + high) / 2;
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
merge(a, low, mid, high);
}
}
int main()
{
int a[100], n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
mergeSort(a, 0, n - 1);
printf("Sorted list in ascending order:\n");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
OUTPUT :
Enter the number of elements: 6
Enter 6 elements:
38 27 43 3 9 82
Sorted list in ascending order:
3 9 27 38 43 82