Merge sort is an efficient sorting algorithm based on merge operations. This algorithm is a very typical application of the Divide and Conquer approach.
First consider how to merge two ordered sequences. This is very simple: just compare the first numbers of the two sequences, take the smaller one first, and delete that number from the corresponding sequence after taking it. Then compare again; if one sequence is empty, just take out the data of the other sequence one by one.
It can be seen that merging ordered sequences is relatively efficient and can reach O(n).
After solving the above problem of merging ordered sequences, let's look at merge sort. Its basic idea is to divide the array into two groups, A and B. If the data within each group is ordered, then these two groups of data can be sorted conveniently. How can the data within these two groups be made ordered?
You can further divide groups A and B into two groups each. And so on. When a divided subgroup has only one data item, the subgroup can be considered already ordered, and then merge the two adjacent subgroups. In this way, merge sort is completed by recursively decomposing the sequence first and then merging the sequences.
The efficiency of merge sort is relatively high. Let the sequence length be N. It takes a total of logN steps to divide the sequence into small sequences. Each step is a process of merging ordered sequences, and the time complexity can be recorded as O(N), so the total is O(N*logN). Because merge sort operates on adjacent data each time, among several sorting methods with O(N*logN) (quick sort, merge sort, shell sort, heap sort), merge sort is also relatively efficient.
On my computer, I compared bubble sort, direct insertion sort, merge sort, and direct use of the system's qsort() (all in Release version).Test with 20,000 random data items:

Test with 50,000 random data items:

Then test with 200,000 random data items:

Note: Some books allocate a temporary array in mergearray() when merging ordered sequences, but too many new operations are very time-consuming. So a small change was made. Only one temporary array is allocated with new in MergeSort(). All subsequent operations share this temporary array.
Author: MoreWindows
Original: https://blog.csdn.net/morewindows/article/details/6678165