2020-03-02
if n == 1 then done
else
B = MergeSort( A[ 1,..., floor(n/2) ] )
C = MergeSort( A[ floor(n/2), ..., n ] )
merge(B, C)
[10] [2] [5] [3] [7] [13] [1] [6]
\/ \/ \/ \/
[2,10] [3,5] [7,13] [1,6]
...
[1, 2, 3, 5, 6, 7, 10, 13]
:
B | C |
---|---|
2 | |
7 | 9 |
| B | C | | ——— | ——— | | |
---|
| B | C | | ——— | ——— | | |
B | C |
---|---|
B | C |
---|---|
13 |
itd…
merge
ma złożoność dla input’u wielkości
iterativeMergeSort(A, n)
inject(Q, x)
- działa jak push
na liście Q
eject(Q)
- działa jak pop
na liście Q
Q = []
for i = 1 to n
inject(Q, A[i])
while |Q| > 1
inject(Q, merge(eject(Q), eject(Q)))
return eject(Q)
:
[10] [2] [5] [3] [7] [13] [1] [6]
[5] [3] [7] [13] [1] [6] [2,10]
[7] [13] [1] [6] [2,10] [3,5]
[1] [6] [2,10] [3,5] [7,13]
[2,10] [3,5] [7,13] [1,6]
[2,3,5,10] [7,13] [1,6]
[2,3,5,7,10,13] [1,6]
[1,2,3,5,6,7,10,13]
done.