Algorithm note-Sort series-merge sort

Source: Internet
Author: User

1. Brief Introduction

Assume that the array to be sorted is int array [] and the array length is N. Merge Sorting is a recursive method.
When N = 1, stop recursion.
When n> 1, open an array of the same size as array, int TMP []
Recursively sorts arrays from array [0] to array [n/2], recursively sorts arrays from array [n/2 + 1] to array [n-1 ].
Use two pointers to add the small elements to the TMP array one by one.
Copy TMP to array and release the TMP array.

2. Complexity

The average time complexity is O (n * logn), and the space complexity is O (n ).
Stability is a stable sorting. Note that when two pointers are compared in the program, if the sizes are the same, you should put the first pointer data in TMP, it can be ensured that the sorting is stable.

3. Code

Void merge_sort (int array [], int n ){
// Recursive termination
If (n <= 1)
Return;
// Recursive sorting
Merge_sort (array, n/2 );
Merge_sort (array + n/2, n-n/2 );
// Merge operations
Int * tmp = new int [n];
Int a = 0;
Int B = n/2;
Int I = 0;
While (a <n/2 & B <(n-n/2 )){
If (array [a] <= array [B]) // here <= ensures stability
Tmp [I ++] = array [a ++];
Else
TMP [I ++] = array [B ++];
}
While (A <n/2 ){
TMP [I ++] = array [A ++];
}
While (TMP [I ++] = array [A ++]) {
TMP [I ++] = array [B ++];
}
For (I = 0; I <n; I ++)
Array [I] = TMP [I];
Delete [] TMP;
}

The last two while statements and one for statement can be copied. You can use memcpy to speed up the process.

4. References

Wikipedia-merge sort http://en.wikipedia.org/wiki/Merge_sort

Related Article

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.