The basic idea of merging and sorting is to divide the array into two groups A and B. If the data in these two groups is ordered, you can sort the data conveniently. How can we make the data in these two groups orderly?
Group A and Group B can be further divided into two groups. And so on. When the split group has only one data, you can think that the group has reached an order, and then merge the two adjacent groups. In this way, the merging order is completed by recursively decomposing the series and then merging the series.
# Include <iostream> # include <string> # include <algorithm> # include <vector> # include <math. h> using namespace STD; void print (int A [], int N) {for (INT I = 0; I <n; I ++) cout <A [I] <"; cout <Endl ;}// there will be two sequential series A [first... mid] And a [Mid + 1... last] merge. Void mergearray (int A [], int first, int mid, int last, int temp []) {int I = first, M = mid; Int J = Mid + 1, N = last; int K = 0; while (I <= M & J <= N) {if (a [I] <A [J]) {temp [k ++] = A [I]; I ++;} else {temp [k ++] = A [J]; j ++ ;}} while (I <= m) {temp [k ++] = A [I]; I ++;} while (j <= N) {temp [k ++] = A [J]; j ++;} // copy back to a for (INT I = 0; I <K; I ++) {A [first + I] = temp [I] ;}} void mergesort (int A [], int first, int last, int temp []) {If (first <last) {int mid = (first + last)/2; mergesort (A, first, mid, temp); mergesort (A, Mid + 1, last, temp); mergearray (A, first, mid, last, temp) ;}} int main () {// test int n = 10; int A [] = {9, 12, 17,30, 50,20, 60,65, 4,19}; int B [] = {9,12, 17,30, 50,4, 20,60, 65,70}; int * temp = new int [N]; mergesort (, 0, N-1, temp); print (temp, n); Return 0 ;}
The efficiency of merging and sorting is relatively high. If the length of a series is set to N, splitting the series into small series requires a total of n logn steps. Each step is a process of merging ordered series, the time complexity can be recorded as O (N), so a total of O (N * logn ). Because Merge Sorting is performed on adjacent data each time, Merge Sorting is performed in several sorting methods (fast sorting, Merge Sorting, Hill sorting, and heap sorting) of O (N * logn) it is also highly efficient.