0% found this document useful (0 votes)
4 views

Merge Sort

This document contains a C program that implements the merge sort algorithm. It allows the user to input an array of integers, sorts the array using merge sort, and then outputs the sorted array. The program includes functions for merging and recursively sorting the array.

Uploaded by

swetha.v
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)
4 views

Merge Sort

This document contains a C program that implements the merge sort algorithm. It allows the user to input an array of integers, sorts the array using merge sort, and then outputs the sorted array. The program includes functions for merging and recursively sorting the array.

Uploaded by

swetha.v
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(int arr[], int l, int m, int r) {


int n1 = m - l + 1, n2 = r - m, L[n1], R[n2];
for (int i = 0; i < n1; i++) L[i] = arr[l + i];
for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);

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

mergeSort(arr, 0, n - 1);

printf("Sorted array: ");


for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");

return 0;
}

You might also like