The merge sort is an efficient sorting algorithm based on the merging operation, and the time complexity is O (NLOGN).
The process is: compare the size of a[i] and a[j], if A[I]≤A[J], the first ordered table elements a[i] copied to r[k], and I and K plus 1; otherwise, the second ordered TABLE element A[j] copied to R[k], and the J and K respectively add 1, so loop down Until one of the ordered tables is finished, and then the remaining elements in the other ordered table are copied to the cell in R from subscript K to subscript T, as shown in.
1#include <stdio.h>2#include <stdlib.h>3 4 intN;5 6 /*7 * Merger8 */9 voidMerge (int*source,int*target,intIintMintN)Ten { One intJ, K; A for(j = m +1, k = i; I <= m && j <= N; k++) - { - if(Source[i] <=Source[j]) the { -Target[k] = source[i++]; - } - Else + { -Target[k] = source[j++]; + } A } at while(I <=m) - { -target[k++] = source[i++]; - } - while(J <=N) - { intarget[k++] = source[j++]; - } to } + - /* the * Merge Sort * */ $ voidMergeSort (int*source,int*target,intSintt)Panax Notoginseng { - intM, *temp; the if(s = =t) + { ATarget[s] =Source[s]; the } + Else - { $temp = (int*)malloc(sizeof(int) * (T-s +1)); $m = (s + t)/2; - mergesort (source, temp, S, m); -MergeSort (source, temp, M +1, T); the Merge (temp, target, S, M, t); - }Wuyi } the - intMain () Wu { - inti; About int*Array; $printf"Please enter the size of the array:"); -scanf"%d", &n); -Array = (int*)malloc(sizeof(int) *n); -printf"Please enter data (separated by spaces):"); A for(i =0; I < n; i++) + { thescanf"%d", &array[i]); - } $MergeSort (array, array,0N1); theprintf"after sorting is:"); the for(i =0; I < n; i++) the { theprintf"%d", Array[i]); - } inprintf"\ n"); the}
Data structure sorting-merge sort