MERGE SORT
The Merge Sort algorithm is a divide-and-conquer algorithm that sorts an
array by first breaking it down into smaller arrays, and then building the array
back together the correct way so that it is sorted.
Principle:
Divide: The algorithm starts with breaking up the array into smaller and
smaller pieces until one such sub-array only consists of one element.
Conquer: The algorithm merges the small pieces of the array back together
by putting the lowest values first, resulting in a sorted array.
The breaking down and building up of the array to sort the array is done
recursively.
Working Procedure:
1. Divide the unsorted array into two sub-arrays, half the size of the original.
2. Continue to divide the sub-arrays as long as the current piece of the array
has more than one element.
3. Merge two sub-arrays together by always putting the lowest value first.
4. Keep merging until there are no sub-arrays left.
Example:
Merge Sort works from a different perspective. The array is split into smaller and
smaller pieces until it is merged back together. And as the merging happens,
values from each sub-array are compared so that the lowest value comes first.
Time Complexity
Best Case: O(n log n) (when the list is already sorted)
Average Case: O(n log n)
Worst Case: O(n log n)
Space Complexity: O(n) (due to temporary arrays during merging)
Advantages:
Stable sort (preserves the order of equal elements)
Predictable time complexity
Efficient for large datasets
Disadvantages:
High space complexity
Slower for small datasets compared to algorithms like Quick Sort or
Insertion Sort
Merge Sort Algorithm:
function mergeSort(arr)
if length of arr ≤ 1
return arr
mid = length of arr / 2
left = mergeSort(arr[0...mid-1])
right = mergeSort(arr[mid...end])
return merge(left, right)