This preview shows pages 1–2. Sign up to view the full content.
COS 226
Algorithms and Data Structures
Spring 2004
Midterm Solutions
1.
9 sorting algorithms.
0425713689
Similar to Spring 2003 exam.
(a) Original input
(b) Insertion: the algorithm has sorted the ﬁrst 12 strings, but hasn’t touched the remaining
23 strings.
(c) Bubble: after 12 phases of bubblesort, the smallest 12 strings are guaranteed to be in
their ﬁnal sorted order (and actually 15 are).
chug
was bubbled down so it’s not selection
sort.
(d) LSD: the strings are sorted on their last character.
(e) MSD. The strings are sorted on their ﬁrst character.
(f) 3way radix quicksort: after 3way partitioning on the
c
in
chug
, all smaller keys are in
the top piece, all larger keys are in the bottom piece, and all keys that begin with
c
are
in the middle piece.
(g) Heapsort: the ﬁrst phase of heapsort puts the keys in reverse order in the heap.
(h) Mergesort: the algorithm has sorted the ﬁrst 18 strings and the last 17 strings. One
ﬁnal merge will put the strings in sorted order.
(i) Quicksort: after partitioning on
chug
, all smaller keys are in the top piece, all smaller
keys are in the bottom piece.
(j) Selection: the smallest 12 strings are in their ﬁnal sorted order.
chug
didn’t move so it’s
not bubble sort.
2.
Analysis of algorithms.
(a)
N
.
There are
n
string concatenations, where the pairs of strings to be concatenated
have lengths 1
,
2
,
4
,... ,N/
2. Thus, the overall running time is proportional to 2 + 4 +
8+
...
+
N
=2
N

2.
(b)
N
2
.
It performs
N
string concatenations where the sums of the lengths of the strings
to be concatenated are 1
,
2
,
3
,... ,N
. The overall running time is proportional to 1 +
2+
...
+
N
=
N
(
N
+1)
/
2.
(c)
N
log
N
.
Each function call makes two recursive calls on inputs half the size, and
combines them with a linear amount of work. You should recognize the running time as
the solution to the classic divideandconquer recurrence, just like mergesort.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview. Sign up
to
access the rest of the document.