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

Mergesort

This document contains a C program that implements the merge sort algorithm. It prompts the user to input the number of elements and their values, sorts the array using the merge sort technique, and then displays the sorted list. The program includes functions for both the merge sort and the merging process.

Uploaded by

Kavya
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)
7 views1 page

Mergesort

This document contains a C program that implements the merge sort algorithm. It prompts the user to input the number of elements and their values, sorts the array using the merge sort technique, and then displays the sorted list. The program includes functions for both the merge sort and the merging process.

Uploaded by

Kavya
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
You are on page 1/ 1

#include <stdio.

h>

void merge_sort(int a[], int low, int high);


void merge(int a[], int low, int mid, int high);

int main() {
int a[10], n;

printf("\nHow many elements: ");


scanf("%d", &n);

printf("\nEnter the elements: ");


for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}

merge_sort(a, 0, n - 1);

printf("\nSorted list is: ");


for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}

return 0;
}

void merge_sort(int a[], int low, int high) {


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

void merge(int a[], int low, int mid, int high) {


int temp[10], i = low, j = mid + 1, k = low;

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; i <= high; i++) {


a[i] = temp[i];
}
}

You might also like