© 2004 Goodrich, Tamassia Merge Sort 1
© 2004 Goodrich, Tamassia Merge Sort 1
7 29 4 2 4 7 9
72 2 7
77
22
Merge Sort
94 4 9
99
44
Divide-and-Conquer ( 10.1.1)
Divide-and conquer is a
general algorithm design
paradigm:
Merge Sort
Merge-sort is a sorting
algorithm based on the
divide-and-conquer
paradigm
Like heap-sort
It uses a comparator
It has O(n log n) running
time
Unlike heap-sort
Merge-Sort
Merge-sort on an input
sequence S with n
elements consists of
three steps:
Algorithm mergeSort(S, C)
Input sequence S with n
elements, comparator C
Output sequence S sorted
according to C
if S.size() > 1
(S1, S2) partition(S, n/2)
mergeSort(S1, C)
mergeSort(S2, C)
S merge(S1, S2)
Merge Sort
Algorithm merge(A, B)
Input sequences A and B with
n/2 elements each
Output sorted sequence of A B
S empty sequence
while A.isEmpty() B.isEmpty()
if A.first().element() < B.first().element()
S.insertLast(A.remove(A.first()))
else
S.insertLast(B.remove(B.first()))
while A.isEmpty()
S.insertLast(A.remove(A.first()))
while B.isEmpty()
S.insertLast(B.remove(B.first()))
return S
Merge Sort
Merge-Sort Tree
An execution of merge-sort is depicted by a binary tree
7 2
9 4 2 4 7 9
2 2 7
77
2004 Goodrich, Tamassia
22
4 4 9
99
Merge Sort
44
5
Execution Example
Partition
7 2 9 43 8 6 1 1 2 3 4 6 7 8 9
7 2 9 4 2 4 7 9
7 2 2 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
6
7 29 4 2 4 7 9
7 2 2 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
7
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
8
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
9
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
10
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
11
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
12
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 8 6
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
13
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 6 8
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
14
7 29 4 2 4 7 9
722 7
77
22
3 8 6 1 1 3 6 8
9 4 4 9
99
44
Merge Sort
3 8 3 8
33
88
6 1 1 6
66
11
15
Analysis of Merge-Sort
The height h of the merge-sort tree is O(log n)
at each recursive call we divide in half the sequence,
n/2
2i
n/2i
Merge Sort
16
merge-sort
2004 Goodrich, Tamassia
Time
Notes
O(n2)
slow
in-place
for small data sets (< 1K)
O(n2)
slow
in-place
for small data sets (< 1K)
O(n log n)
fast
in-place
for large data sets (1K 1M)
O(n log n)
fast
sequential data access
for huge data sets (> 1M)
Merge Sort
17
Nonrecursive Merge-Sort
merge runs of
length 2, then
4, then 8, and
so on
Merge Sort
18