Merge sort splits the array in half, sorts each half, and merges the two sorted halves back together. Because each level of splitting halves the problem, it sorts n values in O(n log n) time, every time, which is far faster than selection or insertion sort on large arrays.
Merge sort is a divide and conquer algorithm. To sort arr[left..right]:
mid = left + (right - left) / 2, splitting the range into a left half and a right half.The recursion stops at the base case: a range with one element (or none) is already sorted, so there is nothing to do. All the real work happens in the merge step.
Merging two sorted lists is easy because their smallest values are at the front. Compare the two front values, copy the smaller one out, and move past it. Repeat until one list is used up, then copy the rest of the other. Each comparison places one value, so merging k values takes at most k − 1 comparisons.
Sorting {38, 27, 43, 3, 9, 82, 10}. Going down, each range is split in half until only single values are left. Going up, neighboring pieces are merged into sorted runs.
The array in main() changes to match what you sort.
The number of levels. Each split halves the range, so after about log₂ n levels every piece has one element. Seven values need 3 levels; a million values need only 20.
The work per level. On any one level, the merges together handle every value once, so each level costs about n steps.
Multiply the two: about n values × log₂ n levels. As a recurrence, the time to sort n values is
Merge sort always splits in the middle and always merges, whatever the data, so this holds in the best, average and worst case.
Memory. The merge step copies each half into temporary vectors, so merge sort needs O(n) extra space. It is not in place, unlike selection and insertion sort.
Stability. When the two front values are equal, the merge takes the one from the left half first (L[i] <= R[j]). Equal values therefore keep their original order: merge sort is stable. Try the Equal values preset.
Merge sort is run on random arrays of each size and its comparisons are counted. Selection sort always makes n(n − 1)/2.
A range with left >= right has at most one element. A single value is in order by itself, so mergeSort returns without doing anything.
Six. 3 vs 9, 27 vs 9, 27 vs 10, 27 vs 82, 38 vs 82, 43 vs 82. Then the left half is used up and 82 is copied without a comparison. Merging k values takes at most k − 1 comparisons.
They give the same answer, but left + right can overflow an int for very large arrays. right - left never does.
With L[i] < R[j], a tie would take the value from the right half first, so equal values could swap order. The sort would still be correct, but no longer stable.