Common sorting algorithms -- Merge Sorting

Source: Internet
Author: User

Principles of Merge Sorting:

If the number of elements in the array is greater than 1, then:

Divide the array into two parts equally;

Array merging and sorting on the left; Recursion

Array merging and sorting on the right; Recursion

Merge two sorted arrays. An additional secondary array is required to save the merging result temporarily.

Otherwise, when the number of array elements is 1, it is ordered; return directly.

 

Stable sorting. The time complexity is O (n lgn) at the worst, best, and average, and the space complexity is O (n ).

 

Code:

1 # include <iostream> 2 using namespace STD; 3 4 template <typename T> 5 void mergesortedarray (t src [], int first, int mid, int last, t TMP []) 6 {7 int I = first, j = Mid + 1; 8 int idx = 0; 9 10 while (I <= Mid & J <= last) 11 {12 TMP [idx ++] = SRC [I] <SRC [J]? SRC [I ++]: SRC [J ++]; 13} 14 15 while (I <= mid) 16 {17 TMP [idx ++] = SRC [I ++]; 18} 19 while (j <= last) 20 {21 TMP [idx ++] = SRC [J ++]; 22} 23 24 for (I = 0; I <idx; ++ I) 25 {26 SRC [first + I] = TMP [I]; 27} 28} 29 30 template <typename T> 31 void mergesort (T SRC [], int first, int last, t TMP []) 32 {33 If (first> = last) 34 return; 35 36 int mid = first + (last-first)> 1 ); // locate the subscript of the intermediate element and divide the array into two parts: 37 38 mergesort (SRC, first, mid, TMP); // sort the left-side sub-array 39 mergesort (SRC, Mid + 1, last, TMP); 40 41 mergesortedarray (SRC, first, mid, last, TMP); // merge, TMP is the auxiliary array, result 42} 43 44 int main () 45 {46 const int n = 5; 47 48 int Ia [N] = {1, 3, 6, 2, 4}; 49 int itmp [N]; 50 mergesort (IA, 0, n-1, itmp); // sort51 for (INT I = 0; I <N; ++ I) 52 cout <Ia [I] <''; 53 cout <Endl; 54 55 double da [N] = {1.2, 3.4, 6.7, 2.3, 4.5}; 56 double dtmp [N]; 57 mergesort (DA, 0, n-1, dtmp); // sort58 for (INT I = 0; I <N; ++ I) 59 cout <da [I] <''; 60 cout <Endl;
61 Return 0;
62}

 

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.