Merge Sort Algorithm Details
Merge Sort Algorithm Details
1. Introduction:
Merge Sort is a highly efficient and stable sorting algorithm that uses the divide-and-conquer
paradigm. Developed by John von Neumann in 1945, it works by recursively dividing the array into
two halves, sorting each half, and then merging the sorted halves back together.
2. Problem Statement:
Given an unsorted array of n elements, the task is to sort the elements in ascending order using the
3. Technique:
Merge Sort divides the array into two halves, recursively sorts them, and then merges the sorted
halves to produce the final sorted array. This merging process ensures that the array becomes
4. Steps:
- Divide the unsorted list into n sublists, each containing one element.
- Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining.
5. Algorithm:
6. Implementation in C:
#include <stdio.h>
int n1 = m - l + 1;
int n2 = r - m;
int i = 0, j = 0, k = l;
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = R[j];
j++;
k++;
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
printf("\n");
int main() {
printArray(arr, arr_size);
return 0;
7. Implementation in Python:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
arr[k] = L[i]
i += 1
k += 1
arr[k] = R[j]
j += 1
k += 1
merge_sort(arr)
8. Implementation in Java:
public class MergeSort {
int n1 = m - l + 1;
int n2 = r - m;
int i = 0, j = 0, k = l;
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
k++;
i++;
k++;
arr[k] = R[j];
j++;
k++;
if (l < r) {
int m = l + (r - l) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
int n = arr.length;
ob.sort(arr, 0, n - 1);
System.out.println("Sorted array:");
9. Expected Output:
Sorted array: 5 6 7 11 12 13
10. Advantages:
- Stable sort.
11. Disadvantages:
13. Conclusion:
Merge Sort is a powerful and reliable sorting algorithm that consistently provides good performance.
Its stability and predictable time complexity make it ideal for many critical applications, especially
when large datasets or stability requirements are involved. Despite requiring additional memory, it is