Two-way merge sort of sorting algorithm

Source: Internet
Author: User

Basic ideas

The sequence of elements to be sorted is first divided into two sub-sequences of equal length, sorted for each subsequence, and then merged into a sequence.

Code
Private void MergeSort(int[] A,int[] B,intLeftintright) {if(Left < right) {intMiddle = (left + right)/2;        MergeSort (A, B, left, middle); MergeSort (A, B, Middle +1, right);    Merge (A, B, left, middle, right); }}Private void Merge(int[] A,int[] B,intLeftintMiddle,intright) {if(Left < right) {intP, q, t;        p = left; Q = middle +1; T = left; while(P <= Middle && Q <= right) {if(A[p] <= a[q])            {b[t++] = a[p++]; }Elseb[t++] = a[q++]; } while(P <= middle) b[t++] = a[p++]; while(q <= right) b[t++] = a[q++]; for(intK = left; K < T;    k++) A[k] = b[k]; }}
Performance analysis
  • Complexity of Time
    The time required for two-way merge sorting mainly includes the time of dividing two sub-sequences, the time of sorting the two sub-sequences and the merging time respectively. The time to divide the sub-sequence is a changshu, can not be considered, the last time required to merge with the number of elements n linear correlation, therefore, for a length of n sequence of elements to merge the time cost is T (N)=CN+2T (N/2) 。 Since the merge sort does not depend on the initial input arrangement of the original ordered element sequence, the length of the two subsequence is basically the same at each partition, so the best, worst, and average time complexity of the merge sort is O(NLo g 2 N) 。
  • Complexity of space
    It requires a secondary space as large as the original array to be sorted.
  • Stability
    Merge sort is a kind of stable sorting algorithm.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Two-way merge sort of sorting algorithm

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.