5_onotation

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: Assume
that
the
target
is
not
in
the
array
½
 the
time
 !  Therefore
½
the
time
the
entire
array
has
to
be
 searched
 !  Assume
that
there
is
an
equal
probability
of
 the
target
being
at
any
array
location
 is
at
some
location
i
 John Edgar !  If
it
is
in
the
array
 !  That
is,
there
is
a
probability
of
1/n
that
the
target
 22 !  Work
done
if
the
target
is
not
in
the
array
 !  n
comparisons
 !  This
occurs
with
probability
of
0.5
 John Edgar 23 !  Work
done
if
target
is
in
the
array:
 !  1
comparison
if
target
is
at
the
1st
location
 ▪  Occurs
with
probability
1/n
(second
assumption)
 !  2
comparisons
if
target
is
at
the
2nd
location
 ▪  Also
occurs
with
probability
1/n

 !  i
comparisons
if
target
is
at
the
ith
location
 !  Take
the
weighted
average
of
the
values
to
find
the
 total
expected
number
of
comparisons
(E)
 !  E
=
1*1/n
+
2*1/n
+
3*1/n
+
…
+
n
*
1/n
or
 !  E
=
(n
+
1)
/
2
 John Edgar 24 !  !  !  Target
is
not
in
the
array:
n
comparisons
 Target
is
in
the
array
(n
+
1)
/
2
comparisons
 Take
a
weighted
average
of
the
two
amounts:
 !  =
(n
*
½)
+
((n
+
1)
/
2
*
½)
 !  =
(n
/
2)
+
((n
+
1)
/
4)
 !  =
(2n
/
4)
+
((n
+
1)
/
4)
 !  =
(3n
+
1)
/
4
 !  Therefore,
on
average,
we
expect
linear
search
to
 perform
(3n
+
1)
/
4
comparisons*
 
 *recall
the
assumption
we
made
about
½
not
in
array
 John Edgar 25 !  If
we
sort
the
target
array
first
we
can
change
the
 linear
search
average
cost
to
around
n
/
2
 !  Once
a
value
equal
to
or
greater
than
the
target
is
found
 !  However,
if
the
array
is
sorted,
it
is
possible
to
do
 much
better
than
this
 John Edgar the
search
can
end
 ▪  So,
if
a
sequence
contains
8
items,
on
average,
linear
 search
compares
4
of
them,

 ▪  If
a
sequence
contains
1,000,000
items,
linear
search
 compares
500,000
of
them,
etc.
 26 Search
for
32 
 Guess
that
the
target
item
is
in
the
middle,
that
is
index
=
15
/
2
=
7 
 value index 07 11 15 21 29 32 44 45 57 61 64 73 79 81 0 1 2 3 4 5 6 7 8 9 10 11 12 13 86 14 92 15 The
array
is
sorted,
and
contains
16
items
indexed
from
0
to
15
 John Edgar 27 Search
for
32 
 45
is
greater
than
32
so
the
target
must
be
in
the
lower
half
of
the
array 
 Repeat
the
search,
guessing
the
mid
point
of
the
lower
subarray
(6
/
2
=
3)
 value index 07 11 15 21 29 32 44 45 57 61 64 73 79 81 0 1 2 3 4 5 6 7 8 9 10 11 12 13 86 14 92 15 Everything
in
the
...
View Full Document

This note was uploaded on 04/17/2010 for the course CMPT 11151 taught by Professor Gregorymori during the Spring '10 term at Simon Fraser.

Ask a homework question - tutors are online