Since the play ACM has been a sort of merger for a long time, now write a blog to introduce this algorithm:)
The picture is from Wikipedia, showing the complete merge sort process. For example, the array {38, 27, 43, 3, 9, 82, 10}.
In the introduction of algorithms, the chapter of Divide and conquer is referred to merge sort. First, the merge sort is a divide-and-conquer algorithm.
The merge (merge) Sort method combines two (or more than two) ordered tables into a new ordered table.
That is, the ordered sequence is divided into several ordered sub-sequences, and then the orderly subsequence is merged into a whole ordered sequence.
The Merg () function is used to merge two ordered arrays. is the key to the entire algorithm.
So what's the use of merge sorting?
- Sorting elements in an array by row
- Sorting the elements in the list by row, other sorting algorithms such as heap sorting and quick sorting cannot sort the list (refer to my blog http://www.cnblogs.com/wushuaiyi/p/4558391.html)
- Can find the number of reverse order (refer to my blog http://www.cnblogs.com/wushuaiyi/p/4362149.html)
- Sort outside
Below is a version of the merge sort that I wrote using the C + + implementation:
#include <iostream>using namespacestd;Const intMAXN =10900;intA[MAXN], TMP[MAXN], N;voidMerge (intLintMintr) {inti =l; intj = m +1; intK =l; while(I <= m && J <=r) {if(A[i] <A[j]) {Tmp[k+ +] = a[i++]; } Else{tmp[k+ +] = a[j++]; } } while(I <=m) {tmp[k+ +] = a[i++]; } while(J <=r) {tmp[k+ +] = a[j++]; } for(inti = l; I <= R; ++i) a[i]=tmp[i];}voidMerge_sort (intLintr) {if(L <r) {intm = (L + r) >>1; Merge_sort (L, M); Merge_sort (M+1, R); Merge (L, M, R); }}intMain () {Std::ios::sync_with_stdio (false); intI, J, T, K, u, c, V, p, numcase =0; while(Cin >>N) { for(i =0; I < n; ++i) {cin>>A[i]; } merge_sort (0N1); for(i =0; I < n; ++i) {cout<< A[i] <<Endl; } } return 0;}
The efficiency of merge sort is relatively high, set the series length as N, divide the series into small series to Logn step,
Each step is a process of merging ordered series, and the time complexity can be recorded as O (N), so it is O (N*logn) altogether.
Because the merge sort is always done in the adjacent data,
So merge sort in O (N*logn) Several sort methods (quick sort, merge sort, hill sort, heap sort)
is also a high efficiency.
The sorting algorithm of reading notes in the introduction of algorithms-merge sort merge sorting algorithm