Merge Sorting is a sort method implemented using the merge idea. The principle is that assume that the initial sequence contains n records, it can be regarded as n ordered subsequences. The length of each subsequence is 1 and then merged by two, [n/2] [x] indicates the smallest integer not less than x.) an ordered subsequence with a length of 2 or 1 is obtained. Then, the subsequences are merged in pairs ,......, this is repeated until an ordered sequence with a length of n is obtained. This sorting method is called 2-way merge sorting.
# Include <stdio. h> # include <stdlib. h> void swap (int arr [], int I, int j) {int temp; temp = arr [I]; arr [I] = arr [j]; arr [j] = temp;} void Merge (int sr [], int tr [], int I, int m, int n) {int j; int k; int l; for (j = m + 1, k = I; I <= m & j <= n; k ++) {if (sr [I] <sr [j]) tr [k] = sr [I ++]; elsetr [k] = sr [j ++];} if (I <= m) {for (l = 0; l <= m-I; l ++) tr [k + l] = sr [I + l];} if (j <= n) {for (l = 0; l <n-j; l ++) tr [k + l] = sr [j + l] ;}} void MergeSort (int arr [], int arr1 [], int s, int t) {int m; int arr2 [10]; if (s = t) // s = 0 t = 0; // The length to be sorted is 1arr1 [s] = arr [s]; else {m = (s + t)/2; MergeSort (arr, arr2, s, m ); mergeSort (arr, arr2, m + 1, t); Merge (arr2, arr1, s, m, t) ;}} void print (int arr [], int n) {int I; for (I = 0; I <n; I ++) {printf ("% d", arr [I]);} printf ("\ n");} int main () {int arr [] = {9, 1, 5, 8, 3, 7, 4, 6, 2 }; int n = sizeof (arr)/sizeof (arr [0]); int arr1 [9]; printf ("Before sorting: \ n"); print (arr, n ); mergeSort (arr, arr1, 0, n-1); printf ("sorted: \ n"); print (arr1, n); system ("pause"); return 0 ;}
This article is from "Li Haichuan" blog, please be sure to keep this source http://lihaichuan.blog.51cto.com/498079/1282290