Merge sort:归并排序
Animation
An example of merge sort. First divide the list into the smallest unit (1 element), then compare each element with the adjacent list to sort and merge the two adjacent lists. Finally all the elements are sorted and merged.
Merge sort animation. The sorted elements are represented by dots.
A recursive merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort (top-down).
Complexity
| Class | Sorting algorithm |
|---|---|
| Data structure | Array |
| Worst case performance | O(nlogn) |
| Best case performance | O(nlogn) typical, O(n) natural variant |
| Average case performance | O(nlogn) |
| Worst case space complexity | О(n) total, O(n) auxiliary |
Pseudo code
MERGE-SORT(A,p,r)
1 if p<r
2 q = floor((p+r)/2)
3 MERGE-SORT(A,p,q)
4 MERGE-SORT(A,q+1,r)
5 MERGE(A,p,q,r)
MERGE(A,p,q,r)
1 n1 = q-p+1
2 n2 = r-q
3 let L[1..n1+1] and R[1..n2+1] be new arrays
4 for i=1 to n1
5 L[i] = A[p+i-1]
6 for j=1 to n2
7 R[j] = A[q+j]
8 L[n1+1] = Infinite
9 R[n2+1] = Infinite
10 i = 1
11 j = 1
12 for k=p to r
13 if L[i] <= R[j]
14 A[k] = L[i]
15 i = i+1
16 else
17 A[k] = R[j]
18 j = j+1
Figure
Reference
<< Introduction to Algorithms >> Third Edition, THOMAS H. CORMEN, CHARLES E. LEISERSON, RONALD L. RIVEST, CLIFFORD STEIN.
https://en.wikipedia.org/wiki/Merge_sort
本文详细介绍了归并排序算法的基本原理、动画演示及复杂度分析,通过逐步分解和合并列表的方式实现高效排序,特别适合对数据进行大规模排序操作。
248

被折叠的 条评论
为什么被折叠?



