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. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
Conceptually, a merge sort works as follows:
1) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
2) Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.
Class: Sorting algorithm
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:</1b> О(n) total, O(n) auxiliary
Figure above, 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.
Python
1 | from collections import deque |
Made with ❤️ and ☀️ on Earth.