Merge Sort

Merge Sort is an $$O(n \log n)$$ sort that is based on divide and conquer. It is stable, but not adaptive, and uses $$O(n)$$ memory.

=Explanation=

The Merge
A merge is an operation that takes 2 sorted arrays and merges them into 1 sorted array.

One implementation works like this:

Compare the first elements of both arrays.

If the beginning of the first array is smaller, move it to the output.

If not, then move beginning of the second array to the output.

If one array is empty, copy the other one to output.

The sort
Merge sort works like this: if the array length is 1 or less, the sort is done. Otherwise, merge sort the left half (recursively). Merge sort the right half (recursively). Merge the left and right halves.

=Example= Take the array {9, 10, 13, 2, 3, 4, 16, 6, 7, 15, 1, 8, 12, 5, 11, 14}.

First sort the left half {9, 10, 13, 2, 3, 4, 16, 6}.

First sort the left half {9, 10, 13, 2}.

First sort the left half {9, 10}.

First sort the left half {9}. It is already sorted, so done.

Next, sort the right half {10}. It is already sorted, so done.

Next, merge {9 | 10}. results in {9, 10}.

Next, sort the right half {13, 2}.

First sort the left half {13}. It is already sorted, so done.

Next, sort the right half {2}. It is already sorted, so done.

Next, merge {13 | 2}. results in {2, 13}.

Current array: {9, 10, 2, 13, 2, 3, 4, 16, 6, 7, 15, 1, 8, 12, 5, 11, 14}.

Next, merge {9, 10 | 2, 13}. results in {2, 9, 10, 13}.

Next, sort the right half {3, 4, 16, 6}. results in {3, 4, 6, 16}.

Next, merge {2, 9, 10, 13 | 3, 4, 6, 16}. results in {2, 3, 4, 6, 9, 10, 13, 16}.

Next, sort the right half {7, 15, 1, 8, 12, 5, 11, 14}. results in {1, 5, 7, 8, 11, 12, 14, 15}.

Finally, Merge {1, 5, 7, 8, 11, 12, 14, 15 | 2, 3, 4, 6, 9, 10, 13, 16}. results in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}.

Sorted!

=Pseudocode=

Merging function
procedure merge(array arr, int start, int mid, int end) do int left = start int right = mid int to = 0 array temp = array(length: end - start) while left < mid and right < end do if array[left] <= array[right] then temp[to] = array[left] left += 1 else temp[to] = array[right] right += 1 to += 1 while left < mid do temp[to] = array[left] left += 1 to += 1 while right < end do temp[to] = array[right] right += 1 to += 1 copy(from: temp, to: array, from_offset: 0, to_offset: start, length: end - start)

Merge sort
procedure mergesort(array arr, range merge_range) do if length(merge_range) >= 2 then int mid = merge_range.midpoint merge_sort(arr, range(merge_range.start, mid)) merge_sort(arr, range(mid, merge_range.end)) merge(arr, merge_range.start, mid, merge_range.end) end

Binary Merge Sort
Binary mergesort is a variant of mergesort that runs Binary Insertion Sort on sublists less than 64 elements. This improves average-case comparisons, and slightly improves best-case writes.