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: upper
half
of
the
array
can
be
ignored,
halving
the
search
space
 John Edgar 28 Search
for
32 
 21
is
less
than
32
so
the
target
must
be
in
the
upper
half
of
the
subarray Repeat
the
search,
guessing
the
mid
point
of
the
new
search
space,
5 
 The
target
is
found
so
the
search
can
terminate
 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
mid
point
=
(lower
subarray
index
+
upper
index)
/
2 
 John Edgar 29 !  Requires
that
the
array
is
sorted
 !  In
either
ascending
or
descending
order
 !  Make
sure
you
know
which!
 !  A
divide
and
conquer
algorithm
 !  Each
iteration
divides
the
problem
space
in
half
 !  Ends
when
the
target
is
found
or
the
problem
space
 consists
of
one
element
 John Edgar 30 Java public int binSearch(int arr, int target){ int lower = 0; Index
of
the
last
element
in int upper = arr.length - 1; 
the
array
 int mid = 0; while (lower <= upper){ mid = (lower + upper) / 2; if(target == arr[mid]){ return mid; } else if(target > arr[mid]){ Note
the
if,
else
if, lower = mid + 1; 
else
 } else { //target < arr[mid] upper = mid - 1; } } //while return -1; //target not found } John Edgar 31 !  The
algorithm
consists
of
three
parts
 !  Initialization
(setting
lower
and
upper)
 !  While
loop
including
a
return
statement
on
success
 !  Return
statement
which
executes
when
on
failure
 !  !  Initialization
and
return
on
failure
require
the
same
 amount
of
work
regardless
of
input
size
 The
number
of
times
that
the
while
loop
iterates
 depends
on
the
size
of
the
input
 John Edgar 32 !  !  The
while
loop
contains
an
if,
else
if,
else
statement
 The
first
if
condition
is
met
when
the
target
is
found
 !  And
is
therefore
performed
at
most
once
each
time
the
 algorithm
is
run
 !  The
algorithm
usually
performs
5
operations
for
each
 iteration
of
the
while
loop
 !  Checking
the
while
condition
 !  Assignment
to
mid
 !  Equality
comparison
with
target
 !  Inequality

comparison

 !  One
other
operation
(setting
either
lower
or
upper)
 John Edgar 33 !  In
the
best
case
the
target
is
the
midpoint
 element
of
the
array
 !  Requiring
one
iteration
of
the
while
loop
 John Edgar 34 !  What
is
the
worst
case
for
binary
se...
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