Merge Sort
In computer science, a merge sort (also commonly spelled merge
sort) is an O (n log n) comparison-based sorting algorithm. Most
implementations produce a stable sort, which means that the implementation preserves the input
order of equal elements in the sorted output. Merge sort is a divide and conquer algorithm that was invented by John von Neumann in
1945. A detailed description and analysis of bottom-up merge sort appeared
in a report by Goldstone and
Neumann as early as 1948.
Merge sort
|
|
Class
|
|
Data structure
|
|
O(n log n)
|
|
O(n log n) typical,
O(n) natural variant
|
|
O(n log n)
|
|
O(n) auxiliary
|
Example
Algorithm
MERGE (A, p, q, r )
1. n1 ← q − p +
1
2. n2 ← r − q
3. Create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
2. n2 ← r − q
3. Create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
4. FOR i ←
1 TO n1
5. DO L[i] ← A[p + i − 1]
6. FOR j ← 1 TO n2
7. DO R[j] ← A[q + j ]
8. L[n1 + 1] ← ∞
9. R[n2 + 1] ← ∞
10. i ← 1
11. j ← 1
12. FOR k ← p TO r
13. DO IF L[i ] ≤ R[ j]
14. THEN A[k] ← L[i]
15. i ← i + 1
16. ELSE A[k] ← R[j]
17. j ← j + 1
5. DO L[i] ← A[p + i − 1]
6. FOR j ← 1 TO n2
7. DO R[j] ← A[q + j ]
8. L[n1 + 1] ← ∞
9. R[n2 + 1] ← ∞
10. i ← 1
11. j ← 1
12. FOR k ← p TO r
13. DO IF L[i ] ≤ R[ j]
14. THEN A[k] ← L[i]
15. i ← i + 1
16. ELSE A[k] ← R[j]
17. j ← j + 1
No comments:
Post a Comment