分类: C/C++
2011-03-25 13:32:21
归并排序:
分为三步:
1.Divide Step(拆分)
2. Conquer Step(递归)
3.Combine Step(合并)
对数据a[p,r]进行排序:
MERGE-SORT (A, p, r)
1. IF p < r // Check for base case
2. THEN q = FLOOR[(p +
r)/2] // Divide step
3. MERGE-SORT (A,
p, q) // Conquer step.
4. MERGE-SORT (A,
q + 1, r) // Conquer step.
5. MERGE (A,
p, q, r) // Combine step.
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]
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
完整代码: