Assumethatthetargetisnotinthearray thetime

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: 
all
instructions
is
to
focus
 on
an
algorithm's
barometer
instruction
 !  The
barometer
instruction
is
the
instruction
that
is
executed
 !  Though
it
is
often
still
useful
to
do
so
 !  the
most
number
of
times
in
an
algorithm
 !  The
number
of
times
that
the
barometer
instruction
is
 executed
is
usually
proportional
to
its
running
time
 John Edgar 14 !  Let's
analyze
and
compare
some
different
 algorithms
 !  Linear
search
 !  Binary
search
 !  Selection
sort
 !  Insertion
sort
 !  Quick
sort
 John Edgar 15 !  It
is
often
useful
to
find
out
whether
or
not
a
 list
contains
a
particular
item
 !  If
the
array
isn't
sorted
use
linear
search
 !  Start
with
the
first
item,
and
go
through
the
array
 !  Such
a
search
can
either
return
true
or
false
 !  Or
the
position
of
the
item
in
the
list
 comparing
each
item
to
the
target
 !  If
the
target
item
is
found
return
true
(or
the
index
 of
the
target
element)
 John Edgar 17 Java public int linSearch(int arr, int target){ for (int i=0; i < arr.length; i++){ if(target == arr[i]){ The
function
returns
as
soon
as return i; 
the
target
item
is
found
 } } //for return -1; //target not found } return
‐1
to
indicate
that
the 
item
has
not
been
found
 John Edgar 18 !  !  Iterate
through
an
array
of
n
items
searching
for
the
 target
item
 The
barometer
instruction
is
equality
checking
(or
 comparisons
for
short)
 !  x.equals(arr[i]); //for an object or !  x == arr[i]; //for a primitive type !  There
are
actually
two
other
barometer
instructions,
what
 !  How
many
comparisons
does
linear
search
do?
 John Edgar 19 are
they? !  Best
case
 Worst
case
 !  The
target
is
the
first
element
of
the
array
 !  Make
1
comparison
 !  The
target
is
not
in
the
array
or
 !  The
target
is
at
the
last
position
in
the
array
 !  Make
n
comparisons
in
either
case
 !  Is
it
(Best
case

+
Worst
case)
/
2,
so
(n+
1)
/
2?
 !  !  Average
case
 John Edgar 20 !  There
are
two
situations
when
the
worst
case
 arises
 To
calculate
the
average
cost
we
need
to
know
 how
often
these
two
situations
arise
 !  We
can
make
assumptions
about
this
 !  Though
any
these
assumptions
may
not
hold
for
a
 !  When
the
target
is
the
last
item
in
the
array
 !  When
the
target
is
not
there
at
all
 !  particular
use
of
linear
search
 John Edgar 21 !...
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