Principle
When sorting arrays by using a pure merge method, the array is divided until only one number is left in each array, then the partition is stopped, and then the partitioned array 22 is merged; until all the queues are merged, the merge sort is complete.
Improved
Merge sorts are mostly used in conjunction with other sorts, such as: quick sort and insert sort. That is, when the merging process of the array to a certain extent, the use of a quick sort or insert sort, each data segment is sorted, and then the sorted array together, thus reducing the aggregation of the array of steps and merge steps, greatly improving the efficiency of the sorting.
Analysis
The process of dividing and merging arrays in the process of merging and sorting, so its time complexity is O(nlog2n), which divides the array and merges the array, Within the original array, the spatial complexity is O(nlog2n).
C Language Implementation
Void merge_arr (int *arr, int begin, int mid, int end) { int a1_l = begin; int a1_r = mid; int a2_l = mid + 1; int a2_r = end; int *tmp = NULL; int i = 0, K = 0; if (null == arr | | begin >= end ) { return ; } tmp = (int *) Malloc (sizeof (int) * (end - begin + 1)); while (a1_l <= a1_r && a2_l <= a2_r) { if (arr[a1_l] < Arr[a2_l]) { tmp[i++] = arr[a1_l++]; }else{ tmp[i++] = arr[a2_l++]; } } while (a1_l <= a1_r) { tmp[i++] = arr[a1_l++]; } while (a2_l <= a2_r) { tmp[i++] = arr[a2_l++]; } for (k = 0; k < i; ++k) { arr[begin+k ] = tmp[k]; } free (TMP);} Void part_arr (int *arr, int begin, int end) { int mid = 0; if (null != Arr && begin < end) { mid = begin + ((end - begin) >> 1); part_arr (Arr, begin, mid); part_arr (arr, mid+1, end); merge_arr (Arr, begin, mid, end); }}void merge_sort (int *arr, int begin, int End) { if (null == arr | | begin >= end) { return; } part_arr (arr, begin, end);}
This article is from the "11219885" blog, please be sure to keep this source http://11229885.blog.51cto.com/11219885/1751537
Sorting algorithm--merge sort