algorithm

Merge sort

Merge Sort  
Data structure Array
Worst-case performance O(n log n)
Best-case performance O(n log n) typical, O(n) natural variant
Average performance O(n log n)
Worst-case space complexity О(n) total with O(n) auxiliary, O(1) auxiliary with linked lists

In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output.

img

An example of merge sort. First divide the list into the smallest unit (1 element), then compare each element with the adjacent list to sort and merge the two adjacent lists. Finally all the elements are sorted and merged.

img

A recursive merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort (top-down).

img

Implementations

Language Source
merge_sort.c
merge_sort.cpp
MergeSort.java
 
merge-srt