Algorithm learning Note (iv): merge sort

Source: Internet
Author: User

Algorithm idea: The basic idea is the divide-and-conquer algorithm, that is, a problem is divided into a number of smaller parts of the recursive solution. The specific to the merge sort is to divide the ordered sequence into small sequences, recursively to sort, and then merge.

Steps:

1. Decomposition: Divide n elements into sub-sequences containing N/2 elements

2. Solve: Recursively sort two sub-sequences with merge sort

3. Merging: Merging two sorted sub-sequences to get sorted results

When a subsequence is sorted, its length is 1 o'clock recursion ends.

Algorithmic complexity: O (NLGN)

Code implementation:

voidDivide_sort (intArr[],intPintR) {    if(p<r) {intQ = (r + P)/2;        Divide_sort (arr, p, q); Divide_sort (arr, q+1, R);    Merge_sort (arr, p, Q, R); }}voidMerge_sort (intArr[],intPintQintR) {    intN1 = Q-p +1; intN2 = R-Q; int*l =New int[N1]; int*r =New int[N2]; memcpy (L, arr+p, n1*sizeof(int)); memcpy (R, arr+q +1, n2*sizeof(int)); intI, J; I= j =0; intK =p;  while(i!=n1&&j!=n2) {        if(l[i]<=R[j]) {Arr[k+ +] = l[i++]; }        Else{arr[k+ +] = r[j++]; }    }     while(i!=N1) {Arr[k+ +] = l[i++]; }     while(j!=n2) {Arr[k+ +] = r[j++];    } delete[] L; Delete[] R;}

Algorithm learning Note (iv): 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.