Two-way merge & amp; insert merge & amp; merge in situ, two-way merge sort

Source: Internet
Author: User

Two-way merge & Insert merge & in-situ merge, two-way merge sort

Insert and merge

The time complexity of Merge Sorting is O (nlgn), and the space complexity is O (n );

However, sorting based on a single record that is merged by two is not particularly advocated. A common improvement is to combine insertion sorting, that is, we first use the insert sort to obtain a long ordered subsequence, and then merge them in two (the improved merge is also stable, because the insert sort is stable ). There is a reason for this improvement: although the worst case of insertion sorting is O (n ^ 2), it seems to be greater than the worst case of merge O (nlgn), but normally, because the constant factor of insertion sorting makes it run faster when n is relatively small, it is more appropriate to adopt insertion sorting when the sub-problem is small enough.

Complexity Analysis

The following analysis shows the complexity of the worst case of insert-Merge Sorting: assume that the length of the entire sequence is n. when the length of the sub-sequence is k, the insertion sorting policy is adopted, there is a total of n/k subsequences.

Complexity of sub-sequence completion sorting: In the worst case, the time complexity of n/k sub-sequence completion sorting is O (nk ). Proof: The insertion sorting complexity of each sub-sequence is O (k ^ 2). A total of n/k sub-sequences are therefore O (nk ).

Complexity of merging sub-sequences: In the worst case, the time complexity of merging two sub-sequences is O (n), a total of n/k sub-sequences are merged, lg (n/k) merging is required, so the complexity of merging these subsequences is O (nlg (n/k )).

Therefore, the worst case of improved insert/Merge Sorting is O (nk + nlg (n/k). Here, the maximum value of k cannot exceed lgn, obviously, if k is greater than lgn, the complexity is not the same as merging. That is to say, if a 1000-length array is used, the maximum length of the subsequence cannot exceed 10 when the insertion policy is used to sort the subsequence.

/* Binary Merge Sorting */void Merge (int * array, int low, int middle, int high) {int * temp = new int [sizeof (int) * (high-low + 1)]; int first = low; int second = middle + 1; int I = 0; while (first <= middle & second <= high) {if (array [first] <array [second]) {temp [I ++] = array [first ++];} else {temp [I ++] = array [second ++] ;}} while (first <= middle) {temp [I ++] = array [first ++];} while (second <= high) {temp [I ++] = array [second ++];} memcpy (array + low, temp, sizeof (int) * (high-low + 1); delete [] temp;} void MergeSort (int * array, int begin, int end) {// cout <sizeof (array) <endl; if (end-begin)> 0) {int mid = begin + (end-begin) /2; MergeSort (array, begin, mid); MergeSort (array, mid + 1, end); Merge (array, begin, mid, end );}} /* improved merge algorithm: insert and merge * Get a long sorted string by inserting and sorting, and then merge * that is, when the length of the decomposed array is smaller than a certain value, it will not be decomposed, use Insert sorting instead */# define INSERT_BOUND 5 void InsertSort (int arr [], int beg, int end) {for (int I = beg + 1; I <= end; ++ I) {int temp = arr [I]; int j = I-1; while (j> = beg & arr [j]> temp) {arr [j + 1] = arr [j --];} arr [j + 1] = temp;} void Insert_MergeSort (int arr [], int beg, int end, int temp_arr []) {if (end-beg + 1 <= INSERT_BOUND) {InsertSort (arr, beg, end);} else {int mid = (beg + end) /2; Insert_MergeSort (arr, beg, mid, temp_arr); Insert_MergeSort (arr, mid + 1, end, temp_arr); Merge (arr, beg, mid, end, temp_arr );}}

Merge in situ

Compared with the fast sorting, Merge Sorting requires an extra space of O (n), which once became the disadvantage of merge, but it is good that Merge Sorting can also be sorted in situ, use only the extra space of O (1. 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.

We know that, whether it is based on the merge of individual records or using the insert sort to first obtain a long sub-sequence and then merge it, in the process of algorithm merge, we are merging two adjacent ordered subsequences ".

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;After B, we know that the value before pointer I 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 that the elements before the pointer I are the smallest of the two sequences, that is, the 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.


Void Revere (int * array, int begin, int end) {int temp; while (begin <end) {temp = array [begin]; array [begin] = array [end]; array [end] = temp; begin ++; end --;}} /* array is the starting position of the in array with a rotation. middle is the starting position of the second half. end is the starting position of the second half. */void Rotate_right (int * array, int begin, int middle, int end) {Revere (array, begin, middle); Revere (array, middle + 1, end); Revere (array, begin, end );} void Merge_second (int * array, int begin, int end) {int middle = begin + (end-begin)/2 + 1; int I = begin; int index; while (middle <= end & I <middle) {while (array [I] <= array [middle] & I <middle) {I ++ ;} index = middle; while (middle <= end & array [middle] <= array [I]) {middle ++;} Rotate_right (array, I, index-1, middle-1); I + = (middle-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); Merge_second (arr, beg, end );}}

For in-situ merge, it is only a means of merging. When merging and sorting is implemented, you can use in-situ merge in the two-way merge, or you can use it in the merge algorithm based on improved insertion sorting, as shown in the code.

If there are two ordered sequences in a number group, how can we combine these two ordered sequences?

Problem description:
Array al [0, mid-1] and al [mid, num-1] are their respective orders, the two sub-ordered segments of array al [0, num-1] merge,
Obtain the overall order of al [0, num-1. The space complexity is O (1 ). Note: The al [I] element supports the '<' operator.

/* Train of Thought: Merge the ordered sequences of two segments in the same array into a sorting method that can be inserted, insert the elements in the second half to the first half to find a proper position for each element in the second half. Then insert the elements in the first half to the second half. */void Merge (int * array, int begin, int end) {int middle = begin + (end-begin)/2 + 1; int I = begin; int temp; while (middle <= end) {temp = array [middle]; if (array [I] <array [middle]) {I ++;} else {int index = middle; while (index! = I) {array [index] = array [index-1]; index --;} array [I ++] = temp; middle ++ ;}}}

Of course, you can also use the above Merge_second function, which is also a method to merge ordered sequences in the same place.



Reference: http://www.ahathinking.com/archives/103.html

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.