9.5 Merge Sorting

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.