ArrayList - Amortizing

ArrayList - Amortizing -...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS
112
:
Data
Structures
 Fall
2011
 Lecture
5:
Tuesday,
Sep
20,
2011
 Array
List
add()
=me
–
A
Closer
Look
 Worst
case
=me
is
O(n),
when
auto‐expanding:
all
n
items
are
copied
to
new
array
 With
an
ini=al
capacity
of
10,
and
doubling
every
=me
when
expanding,
the
 following
graph
shows
the
number
of
array
writes
done
when
adding:
 81
 The
spikes
are
the
worst
 case
#
array
assignments
 41
 #
of
array

 writes
 21
 Most
add()s
are
a
single
 array
assignment
 11
 1
 11th
 21st
 CS112


09/20/11
 41st
 81st
 Sesh
Venugopal
 nth
add
 2
 Array
List
add()
=me
–
Amor=zing
 REDISTRIBUTE/AMORTIZE
(conceptually
only!)
the
array
writes.
Take
away
each
 write
–
except
the
lowest
two
‐
in
a
spike
and
give
it
to
one
of
the
adds
in
the
 subsequent
group
(un=l
the
next
spike)
 21
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 Redistribute
 the
rest
(9),
 giving
1
each
 to
the
12th
 thru
20th
adds
 11th
 21st
 #
of
array

 writes
 11
 Save
2
writes
 for
the
11th
 1
 Do
the
same
for
the
21st:
save
 2,
then
give
away
the
rest
(19)
 to
the
22nd
thru
40th
adds.
 And
for
the
41st:
save
2,
then
 give
away
the
rest
(39)
to
the
 42nd
thru
80th
adds.
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 o
 CS112


09/20/11
 Sesh
Venugopal
 nth
add
 3
 Array
List
add()
=me
–
Amor=zing
 A_er
redistribu=ng,
the
graph
flaaens
out.

 #
of
array

 writes
 1
 What
happens
with
the
last
spike
 (e.g.
81st
add?)
There
may
not
be
 enough
adds
a_er
that
to
distribute
 all
79
“extra”
writes.
 2
 11th
 21st
 41st
 The
last
spike
is
redistributed
among
the
adds
that
appear
BEFORE
it
–
80
units
can
 be
given
to
the
previous
80
adds,
retaining
1.
This
will
make
the
first
10
adds
take
on
 2
units
each,
the
next
70,
3
units
each,
and
the
remaining,
1
unit
each
 #
of
array

 writes
 2
 3
 11th
 1
 This
last
sec=on
has
at
least
one
add
 but
no
more
than
79
 81st
 Since
each
add
is
now
either
1,
or
2
,
or
3
array
assignments,
the
AMORTIZED
=me
 for
each
add
is
therefore
O(1)
 (AMORTIZED
cost
is
different
from
average.
Another
example
of
amor=zed
cost
is
paying
 off
a
loan
in
installments
–
each
installment
$$
is
the
amor=zed
cost
of
the
loan.)
 CS112


09/20/11
 Sesh
Venugopal
 4
 ...
View Full Document

This note was uploaded on 03/29/2012 for the course CS 112 taught by Professor Sesh during the Spring '07 term at Rutgers.

Ask a homework question - tutors are online