Data structure sorting-merge sort

Source: Internet
Author: User

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

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.