0% found this document useful (0 votes)
9 views6 pages

Merge Sort Algorithm and Program

The document explains the Merge Sort algorithm, detailing its step-by-step process of dividing an unsorted array, recursively sorting each half, and merging them back together. It includes pseudocode for the algorithm and a C program implementation that demonstrates how to sort an array using Merge Sort. The program prompts the user for input, sorts the array, and then displays the sorted output.

Uploaded by

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

Merge Sort Algorithm and Program

The document explains the Merge Sort algorithm, detailing its step-by-step process of dividing an unsorted array, recursively sorting each half, and merging them back together. It includes pseudocode for the algorithm and a C program implementation that demonstrates how to sort an array using Merge Sort. The program prompts the user for input, sorts the array, and then displays the sorted output.

Uploaded by

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

Merge Sort Algorithm and

Program
C Programming | Algorithm and Code
Explanation
Merge Sort Algorithm (Step-by-Step)
• 1. Divide the unsorted array into two halves.
• 2. Recursively sort each half using Merge Sort.
• 3. Merge the two sorted halves into a single
sorted array.
• 4. Repeat until the entire array is sorted.
Merge Sort - Pseudocode
mergeSort(arr, l, h):
if l < h:
mid = (l + h) / 2
mergeSort(arr, l, mid)
mergeSort(arr, mid + 1, h)
merge(arr, l, mid, h)

merge(arr, l, mid, h):


Create temp arrays L and R
Merge L and R into original array
Merge Sort - C Program (Part 1)
#include <stdio.h>

int a[20], b[20];

void merge(int l, int mid, int h) {


int i = l, j = mid + 1, k = l;
while (i <= mid && j <= h) {
if (a[i] <= a[j]) b[k++] = a[i++];
else b[k++] = a[j++];
}
while (i <= mid) b[k++] = a[i++];
while (j <= h) b[k++] = a[j++];
for (i = l; i <= h; i++) a[i] = b[i];
}
Merge Sort - C Program (Part 2)
void mergeSort(int l, int h) {
if (l < h) {
int mid = (l + h) / 2;
mergeSort(l, mid);
mergeSort(mid + 1, h);
merge(l, mid, h);
}
}
Merge Sort - C Program (Part 2)
int main() {
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
mergeSort(0, n - 1);
for (i = 0; i < n; i++) printf("%d ", a[i]);
return 0;
}

You might also like