Sort Algorithm Analysis [5]: Merge and sort (with Python & amp; C ++ code), algorithm analysis python

Source: Internet
Author: User

Sort Algorithm Analysis [5]: Merge and sort (with Python & C ++ code), and algorithm analysis with python

Merge and sort: combines two sorted sequences into one.

Algorithm principle

First look at the dynamic diagram:


The algorithm is described as follows:

Algorithm Implementation Python version:

#-*-Encoding: UTF-8-*-def merge_sort (list_one, list_two): # merge and sort list_merge = [] I = 0; j = 0 while I <len (list_one) and j <len (list_two): if list_one [I] <= list_two [j]: list_merge.append (list_one [I]) I + = 1 else: list_merge.append (list_two [j]) j + = 1 print 'I ={}, j = {}'. format (I, j) print list_merge while I <len (list_one): list_merge.append (list_one [I]) I + = 1 while j <len (list_two ): list_merge.append (list_two [j]) j + = 1 return list_merge list_one = [1, 3, 5, 6, 8, 10, 12, 13] list_two = [2, 4, 7, 9, 11, 14, 15, 16, 17, 18] print merge_sort (list_one, list_two)
Result:

>>> ================================ RESTART ================================>>> i = 1, j = 0[1]i = 1, j = 1[1, 2]i = 2, j = 1[1, 2, 3]i = 2, j = 2[1, 2, 3, 4]i = 3, j = 2[1, 2, 3, 4, 5]i = 4, j = 2[1, 2, 3, 4, 5, 6]i = 4, j = 3[1, 2, 3, 4, 5, 6, 7]i = 5, j = 3[1, 2, 3, 4, 5, 6, 7, 8]i = 5, j = 4[1, 2, 3, 4, 5, 6, 7, 8, 9]i = 6, j = 4[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]i = 6, j = 5[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]i = 7, j = 5[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]i = 8, j = 5[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13][1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]>>> 
C ++ version:

# Include <iostream> using namespace std; void print (int st_bf [], size_t size) {for (size_t I = 0; I <size; I ++) {cout <st_bf [I] <"" ;}cout <endl;} void merge_sort (int * list_one, size_t len_list_one, int * list_two, size_t len_list_two) {// merge and sort // apply for the int list_merge space [len_list_one + len_list_two]; size_t I = 0, j = 0, k = 0; // k Save the merged length for (; (I <len_list_one) and (j <len_list_two); ++ k) {if (list_one [I] <= list_two [j]) {list_merge [k] = list_one [I ++];} else {list_merge [k] = list_two [j ++];} cout <"I =" <I <", j =" <j <", k = "<k <endl; print (list_merge, k + 1);} // copy the large tail element sequence while (I <len_list_one) list_merge [k ++] = list_one [I ++]; while (j <len_list_two) list_merge [k ++] = list_two [j ++]; cout <"I =" <I <", j =" <j <", k =" <k <endl; print (list_merge, k);} int main () {int list_one [] = {1, 3, 5, 6, 8, 10, 12, 13}; int list_two [] = {2, 4, 7, 9, 11, 14, 15, 16, 17, 18}; size_t len_list_one = sizeof (list_one)/sizeof (list_one [0]); size_t len_list_two = sizeof (list_two)/sizeof (list_two [0]); merge_sort (list_one, len_list_one, list_two, len_list_two); return 0 ;}
The result is the same as the preceding one.

This article by @ The_Third_Wave (Blog address: http://blog.csdn.net/zhanh1218) original. Otherwise, it will be updated from time to time. please correct me if any error occurs.

If you find that this Blog post is incomplete, it is the reason for me to prevent crawlers from releasing half of the posts first. Please refer to the original author's Blog.

If this blog post is helpful to you, you are not recommended to repost it for a good network environment. We recommend that you add it to your favorites! If you must reprint the content, please include the suffix and the address of this article.



What are the principles of insert sorting, select sorting, fast sorting, and Merge Sorting? Which one requires the largest memory?

Baike.baidu.com/view/58783.htm
Sorting is a type of operation that is often performed in a computer. Its purpose is to adjust a set of "unordered" record sequences to "ordered" record sequences.
Internal sorting and external sorting:
If the sorting process can be completed without access to external storage, the Sorting Problem is called internal sorting;
Otherwise, if the number of records participating in sorting is large and the sorting process of the entire sequence cannot be completed in the memory, this sort problem is called external sorting.
The internal sorting process is a process of gradually expanding the sequence length of records.
There are many inner sorting methods. Different policies can be classified into five types: insertion sorting, selection sorting, exchange sorting, Merge Sorting, and allocation sorting.
Insert sorting mainly includes direct insertion sorting and Hill sorting. Selection sorting mainly includes direct selection sorting and heap sorting. Exchange sorting mainly includes Gas Bubble sorting and fast sorting.
I. Bubble Sorting
A group of unordered data a [1], a [2],... A [n], which needs to be arranged in ascending order. First, compare the values of a [1] and a [2]. If a [1] is greater than a [2], the values of the two are exchanged. Otherwise, the values remain unchanged. Compare the values of a [2] and a [3]. If a [2] is greater than a [3], the values of the two are exchanged. Otherwise, the values remain unchanged. Compare the values of a [3] and a [4], and so on. Finally, compare the values of a [n-1] And a [n. In this case, the value of a [n] must be the largest in this set of data. Then, for a [1] ~ If a [n-1] processes a round in the same way, the value of a [n-1] must be a [1] ~ The largest value in a [n-1. Then, for a [1] ~ A [N-2] handles a round in the same way, and so on. Processing of n-1 round after a [1], a [2],... A [n] is arranged in ascending order.
Advantage: stable, known as the number of comparisons;
Disadvantage: It is slow. Only two adjacent data can be moved at a time, and the number of data moves is large.
Ii. Select sorting
A group of unordered data a [1], a [2],... A [n], which needs to be arranged in ascending order. First, compare the values of a [1] and a [2]. If a [1] is greater than a [2], the values of the two are exchanged. Otherwise, the values remain unchanged. Compare the values of a [1] and a [3]. If a [1] is greater than a [3], the values of the two are exchanged. Otherwise, the values remain unchanged. Compare the values of a [1] and a [4], and so on. Finally, compare the values of a [1] and a [n. After a round of processing, the value of a [1] must be the smallest in this set of data. Then convert a [2] and a [3] ~ If a [n] compares a round with the same method, the value of a [2] must be a [2] ~ The smallest of a [n. Then convert a [3] and a [4] ~ A [n] compares a round with the same method, and so on. Processing of n-1 round after a [1], a [2],... A [n] is arranged in ascending order.
Advantage: stable, the number of comparisons is the same as that of Bubble Sorting;
Disadvantage: relatively slow.
Iii. Insert sorting
A group of sorted data in ascending order is known: a [1], a [2],… A [n], a group of unordered data B [1], B [2],... B [m], which must be combined into an ascending sequence. First, compare the values of B [1] and a [1]. If B [1] is greater than a [1], Skip, compare the values of B [1] and a [2]. If B [1] is still greater than a [2], Skip, until B [1] is smaller than a data in array a [x], a [x] ~ A [n] moves one digit backward, and inserts B [1] to the original position of a [x]. This completes the insertion of B [1. B [2] ~ B [m] is inserted in the same way. (If there is no array a, you can regard B [1] as an array a with n = 1)
Advantages: stable and fast;
Disadvantage: the number of comparisons is not certain. The less the number of comparisons, the more data is moved after the inserted point. Especially when the total amount of data is large, the linked list can solve this problem.
Iv. Reduce incremental sorting
Proposed by hill in 1959, also known as shell sorting ).
A group of unordered data a [1], a [2] ...... the remaining full text>

Merge Sorting Algorithm

Implementation of two merge sorting algorithms: Binary Merge Sorting and basic Merge Sorting (virtual elimination of recursive binary Merge Sorting)
# Define arra_size 1024

Int B [1024]; // use a global variable to avoid overhead caused by re-applying for and releasing space every time in the merge sort.

Template <typename T>
Void Merge (t a [], int l, int m, int h)
{
Int I = l;
Int j = m + 1;
Int k = 0;

While (I <= m & j <= h)
{
If (A [I] <A [j])
{
B [k ++] = A [I];
I ++;
}
Else
{
B [k ++] = A [j];
J ++;
}
}

While (I <= m)
{
B [k ++] = A [I ++];
}

While (j <= h)
{
B [k ++] = A [j ++];
}

For (I = l; I <= h; I ++)
{
A [I] = B [I-l];
}
}

// Implement Merge Sorting

Template <typename T>
Void MergeSort (T a [], int l, int h)
{
Int m = (h + l)/2;
If (l> = h)
{
Return;
}

If (l + 1 = h)
{
If (a [l]> a [h])
{
Std: swap (a [l], a [h]);
}

Return;
}

MergeSort (a, l, m );
MergeSort (a, m + 1, h );
Merge (a, l, m, h );
}

// Merge a into B after step s, and n indicates the size of the array
Template <typename T>
Void Merge2 (T a [], T B [], int s, int n)
{
Int m = 0;

// Merge adjacent data from start to end based on step s
For (int I = 0; I <n; I + = 2 * s)
{
Int j = I; // start position of the first group of numbers merged
Int k = I + s; // start position of the number of the second group merged
Int jE = I + s; // start position of the first group of numbers merged
Int kE = I + 2 * s; // start position of the second group of the merged data

While (j <jE) & (k <kE) & j <n & k <n)
{
If (a [j] <a [k])
{
B [m ++] = a [j];
... The remaining full text>

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.