0% found this document useful (0 votes)
6 views3 pages

AOA Experiment 3

The document provides a C program that implements the Merge Sort algorithm. It includes functions for merging sorted arrays and recursively sorting the array. The program demonstrates sorting an example array and outputs both the unsorted and sorted versions.

Uploaded by

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

AOA Experiment 3

The document provides a C program that implements the Merge Sort algorithm. It includes functions for merging sorted arrays and recursively sorting the array. The program demonstrates sorting an example array and outputs both the unsorted and sorted versions.

Uploaded by

vv376012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Performance Date: __________ Submission Date: ___________

Ex. No Experiment Name

3 Write a program to implement Merge Sort.

Code:
#include <stdio.h>
int b[100]; // or temp[100]; Temporary array
void merge(int arr[], int LB, int mid, int UB) {
int i = LB, j = mid + 1, k = LB;
while (i <= mid && j <= UB) {
if (arr[i] < arr[j]) {
b[k] = arr[i];
i++;
} else {
b[k] = arr[j];
j++;
}
k++;
}
while (i <= mid) { // Copy remaining left half
b[k] = arr[i];
i++;
k++;
}
while (j <= UB) { // Copy remaining right half
b[k] = arr[j];
j++;
k++;
}
for (k = LB; k <= UB; k++) { // Copy back to original array
arr[k] = b[k];
}
}
void mergeSort(int arr[], int LB, int UB) {
if (LB < UB) {
int mid = (LB + UB) / 2;
mergeSort(arr, LB, mid);
mergeSort(arr, mid + 1, UB);
merge(arr, LB, mid, UB);
}
}
int main() {
int arr[] = {31, 12, 55, 29, 67, 48};
int size = 6; //sizeof(arr) / sizeof(arr[0]);
int LB = 0, UB = size - 1;
int i;
printf("Unsorted array: ");
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");

mergeSort(arr, LB, UB);


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

return 0;
}

Output:

You might also like