Merge operations for sorting

Source: Internet
Author: User

The merge operation (merge), also called the merge algorithm, refers to the operation that combines two sorted sequences into one. If there is a series of {6,202,100,301, 8, 1} initial states: [6] [202] [100] [301] [38] [8] [1] comparison times I = 1 [6 202] [100 301] [8 38] [1] 3 I = 2 [6 100 202 301] [1 8 38] 4 I = 3 [1 6 8 38 100 202 301] 4 Total: 11 C language implementation: [cpp] # include <stdio. h> # include <string. h> # include <malloc. h> void display (int array [], int size) {printf ("the array is:"); int I; for (I = 0; I <size; I ++) {printf ("% d", array [I]);} printf ("\ n ");} // merge the first and last ending arrays in array a and put them back into void mergearray (int a [], int first, int mid, int last, int temp []) {int I = first, j = mid + 1; int m = mid, n = last; int k = 0; while (I <= m & j <= n) {if (a [I] <= a [j]) temp [k ++] = a [I ++]; else temp [k ++] = a [j ++];} while (I <= m) temp [k ++] = a [I ++]; while (j <= n) temp [k ++] = a [j ++]; for (I = 0; I <k; I ++) a [first + I] = temp [I];} void sort (int a [], int first, int last, int temp []) {if (first <last) {int mid = (first + last)/2; // sort (a, first, mid, temp); // sort the arrays on the right sort (a, mid + 1, last, temp); // merge the Left and Right arrays into mergearray (a, first, mid, last, temp) ;}} int main (void) {int array [10] = {34, 45, 65,100,}; display (array, 10 ); // apply for a temporary array to store the merged array int * temp = (int *) malloc (sizeof (int) * 10); memset (temp ); // merge algorithm functions sort (array,-1, temp); free (temp); temp = null; display (array, 10); return 0 ;}

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.