In-situ merge sort

Source: Internet
Author: User

In general, when it comes to merge sort, it is natural to think of Divide-and-conqure, O (n lgn) time complexity, and additional O (n) space. O (n) extra space seems to be the most obvious drawback of merge sort, but in fact it can be completely overcome, that is, we can fully implement O (n LGN) time and the merge sort of O (1) space. For this algorithm that does not have extra space (that is, extra space for constant size), there is a generic name called In-place algorithms, so we call the merge algorithm the in-place merge sort, which is the in-place merge order.

The following summarizes the characteristics of in-situ merge sorting:

Space: can be merged without auxiliary array, space complexity is O (1)

Time: Time complexity of O (NLOGN)

The key is the merge function. Two-segment incrementing sub-array arr[begin...mid-1] and arr[mid...end],i=begin,j=mid,k=end

I move backwards to find the index of the first arr[i]>arr[j]


J move backwards, then find the index of the first arr[j]>arr[i]

Then we swapped the part of I to mid and mid to j-1, the smaller part to the front, and then from the back part and the J to the K section were two incrementing sub-arrays, to continue the iteration.


A) Swap rotation

Rotation, also known as cyclic movement, is assumed to have such a sequence: E0, E1, ..., ei-1, ei, ei+1, ..., en-1, en. Now we need to move it to the left by looping the I position into: ei, ei+1, ..., en-1, en, E0, E1, ..., ei-1. In order to save as much memory as possible and to ensure a faster speed, we can achieve the goal in the case of Time complexity O (n), Spatial complexity O (1). A solution is as follows:

Consider the original sequence as two sub-sequences: E0, E1, ..., ei-1 and Ei, ei+1, ..., en-1, en

Turn these two sequences in reverse order: ei-1, ..., E1, E0 and EN, en-1, ..., ei+1, ei

That is to get a sequence: ei-1, ..., E1, E0, en, en-1, ..., ei+1, ei

And then the whole sequence in reverse order: EI, ei+1, ..., en-1, en, E0, E1, ..., ei-1

The time complexity of the above rotation process is O (N/2) + O (N/2) + O (n) = O (2n) = O (n), in reverse order only one element of the auxiliary space, Space complexity O (1).

The following is an example of the idea of in-situ merge sorting.

Before understanding the idea of merging in situ, recall the general merging algorithm, first put the ordered subsequence into a temporary array, and then set two pointers from the beginning of two sub-sequences to find the smallest element into the merge array; so is the idea of merging in place. To ensure that the number before the pointer is always the smallest element in the two subsequence . Words are more useless, see examples of illustrations, one can see.

Let's say we now have two ordered subsequence a, and we're going to start with plot example B for in-place merging


B, first the value of the first subsequence is compared to the first value 20 of the second subsequence, if the value of sequence one is less than 20, then the pointer I moves backwards until a value greater than 20 is found, that is, pointer I moves to We know that the value before the pointer I must be the smallest block in the two sub-sequence.

C, a temporary pointer is used to record the position of J, and then the second sub-sequence of the value of the sequence I refers to a value of 30 compared, if the value of sequence two is less than 30, then J-shift, until a value greater than 30 is found, that is, J moves to 55 subscript;

D, through the process of Figure C, we know that the values in the array block [index, J] must be all less than the value 30 referred to by pointer I, that is, the values in the array block [index, J] are all smaller than the array block [I, index] , in order to satisfy the principle of in- place merging: Always ensure that the element before pointer i is the smallest element in the two sequence, that is, before I is a well-merged element. we swap the memory blocks of these two arrays, and after swapping I move the corresponding steps, this "step" is actually the number of values that the step is merged into, that is, the number of array blocks [index, J] . Thus get figure E as follows:

Repeating the above process, F, is equivalent to the process of Figure B, until finally, this is an implementation of the idea of in-situ merging, the specific code is as follows.

#include <iostream>#include<algorithm>using namespacestd;//reverse an array of length nvoidReverseint*a,intN) {    intI=0; intj=n-1;  while(i<j) {Swap (a[i],a[j]); I++; J--; }}//Loop the array to the left by shifting the I positionvoidExchangeint*a,intNinti)    {reverse (a,i); Reverse (A+i,n-i); Reverse (a,n);}//merging of two ordered parts of an arrayvoidMerge (int*a,intBeginintMidintend) {    intI=begin; intj=mid; intk=end;  while(i<j&&j<=k) {intstep=0;  while(i<j&&a[i]<=A[j]) I++;  while(j<=k&&a[j]<A[i]) {J++; Step++; Exchange (A+i,j-i,j-i-step); I=i+step; }}voidMergeSort (int*a,intLintR) {    if(l<r) {intMid= (L+R)/2;        MergeSort (A,l,mid); MergeSort (A,mid+1, R); Merge (A,l,mid+1, R); }}intMain () {intarr[]={0,1,5,6,9,2,3,4,7,4,1,8}; intlen=sizeof(arr)/sizeof(arr[0]);  for(intI=0; i<len;i++) {cout<<arr[i]<<" "; } cout<<Endl; MergeSort (arr,0, len-1);  for(i=0; i<len;i++) {cout<<arr[i]<<" "; } cout<<Endl; return 0;}

*******************************************************

 PackageBase;Importjava.util.Arrays;/*** Created by Damon on 9/18/16. * In-situ merge sort*/ Public classInplacemergesort {//See:http://www.cnblogs.com/xiaorenwu702/p/5880841.html     Public Static voidMain (string[] args) {intA[] = {49, 38, 65, 97, 76, 13, 27, 49, 78, 49, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51};    MergeSort (a); }    Private Static voidSWIP (int[] A,intPintq) {        inttemp =A[p]; A[P]=A[q]; A[Q]=temp; }    Private Static voidReverseint[] A,intPintq) {        inti =p; intj =Q;  while(i<j)            {Swip (A,I,J); I++; J--; }    }    Private Static voidExchangeint[] A,intPintQintR)        {reverse (A,P,Q); Reverse (a,q+1, R);    Reverse (A,P,R); }     Public Static voidMergeSort (int[] a) {Realmergesort (A,0,a.length-1); System.out.println ("Mergesort-->>" +arrays.tostring (a)); }    Private Static voidRealmergesort (int[] A,intPintR) {        if(p<R) {            intq= (p+r)/2;            Realmergesort (A,P,Q); Realmergesort (A,q+1, R);        Merge (A,p,q,r); }    }    Private Static voidMergeint[] A,intPintQintR) {        intQ1 = q+1; intStep=0;  while(p<=q&&q1<=R) {             while(p<=q&&a[p]<=A[Q1]) {P++; }             while(q1<=r&&a[q1]<A[p]) {Q1++; Step++; } Exchange (A,p,q,q1-1); P=p+step; }    }}

In-situ 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.