In-situ merging and sorting

Source: Internet
Author: User
We have discussed the sorting of arrays and linked lists. The array is merged and sorted by the space complexity of O (n. To solve the problem of in-situ Merge Sorting, only the space complexity of O (1) is used to solve the Merge Sorting of arrays.


The core idea of in-situ Merge Sorting is to reverse the memory variation, that is, to swap two adjacent memory blocks, I once analyzed an interview question in the article "thinking about reverse strings (reverse words) and three solutions. This idea is often used in many places. It is called the "hand shake algorithm" in "programming Pearl ". There are many variants of in-situ merge by means of the SWAp memory of the hand shake algorithm. We will give an example to analyze a common situation, different methods are also based on the Binary Search Method to Determine the swap memory block. In computer programming art, there are also different ideas to provide. For more information, see references in this article.

The following is an example of the concept of in-situ Merge Sorting.

Before learning about the concept of in-situ merging, let's first recall the general merging algorithm. First, we put the ordered subsequences into temporary arrays respectively, then set the two pointers to search for the smallest elements from the beginning of the two sub-sequences and put them in the merged array. So is the idea of in-situ merging, that is, when mergingMake sure that the number before the pointer is always the smallest of the two subsequences.. It is useless to describe the text. For more information, see the sample illustration.

Assume that we now have two ordered subsequence A, starting with the example B of the in-situ merge.

 

B. First, the value of the first subsequence is compared with the first value 20 of the second subsequence. If the value of sequence 1 is less than 20, the pointer I moves backward, until a value greater than 20 is found, that is, the pointer I is moved to 30;AfterB, We know the pointerIThe previous value must be the smallest block in two subsequences.

C. First Use a temporary pointer to record the position of J, and then compare the value of the second sub-sequence with the value 30 in sequence I. If the value of sequence II is less than 30, then J moves backward, until a value greater than 30 is found, that is, the subscript where J moves to 55;

D. Through the process in Figure C, we know the array Block[Index, J)The values in must be all less than the value 30 indicated by pointer I, that is, the array block.[Index, J)All values in are smaller than array blocks.[I, index)To meetPrinciple of in-situ merging: Always ensure pointerElements before I are the smallest of the two sequences, that is, elements that have been merged before I.We swap the memory blocks of these two arrays. After the swap, I move the corresponding number of steps. This "number of steps" is actually the number of values merged in this step, that is, the array block.[Index, J). Figure E is shown as follows:

 

 

Repeat the above process. F is equivalent to the process in Figure B until the end. This is an implementation idea of in-situ merging. The specific code is as follows.

12345678910111213141516171819202122232425262728293031323334353637383940414215253545556575859606162636465666768697071727374 /* Merge in situ* It can be merged in two ways or combined with insertion sorting, such as code*///reverse arrayvoid reverse(int arr[], int size){    int left = 0;    int right = size -1;    while(left < right)    {        int temp = arr[left];        arr[left++] = arr[right];        arr[right--] = temp;    }} // swap [arr,arr+headSize) and [arr+headSize,arr+headSize+endSize)void SwapMemory(int arr[], int headSize, int endSize){    reverse(arr, headSize);    reverse(arr + headSize, endSize);    reverse(arr, headSize + endSize);} void Inplace_Merge(int arr[], int beg, int mid, int end){    Int I = beg; // indicates ordered string 1    Int J = Mid + 1; // indicates the ordered string 2    While (I <J & J <= END) // condition for the end of an in-situ merge.    {        while(i < j && arr[i] <= arr[j])        {            ++i;        }        int index = j;        while(j <= end && arr[j] <= arr[i])        {            ++j;        }        SwapMemory(&arr[i], index-i, j-index);//swap [i,index) and [index,j)        i += (j-index);    }} void Inplace_MergeSort(int arr[], int beg, int end){    if(beg < end)    {        int mid = (beg + end) / 2;        Inplace_MergeSort(arr, beg, mid);        Inplace_MergeSort(arr, mid+1, end);        Inplace_Merge(arr, beg, mid, end);    }} /* Simple test cases */void main(){    int arr[] = {3,5,1,7,0,6,9,11,8};    int temp_arr[] = {3,5,1,7,0,6,9,11,8};     /* Test different merge algorithms */    //MergeSort(arr,0,8,temp_arr);    //Insert_MergeSort(arr,0,8,temp_arr);    //Inplace_MergeSort(arr,0,8);     for(int i = 0; i < 9; ++i)    {        cout<<arr[i]<<" ";    }    cout<<endl;}

Transferred from

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.