Binary Search
Consider an array
a
1
,
a
2
, …,
a
n
of numbers sorted in increasing order
, and
suppose we want to know if a particular number
b
appears in the array.
The following algorithm returns
True
if
b
appears, and returns
False
otherwise.
1: BinarySearch(a
1
, a
2
, ..., a
n
: array of reals, b : real)
2:
lo := 1; hi := n
3:
while lo <= hi
4:
mid :=
(lo + hi)/2
5:
if a
mid
= b then return True
6:
else if a
mid
< b then lo := mid + 1
7:
else hi := mid – 1
8:
end while
9:
return False
Explanation
: Look at the midpoint and if
a
mid
=
b
(line 5) then we return
True
. Otherwise, if
a
mid
<
b
(line 6) then look in the range
a
mid+1
, …,
a
n
and if
a
mid
>
b
(line 7) then look in the range
a
1
, …,
a
mid
−
1
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Running time analysis of Binary Search
Clearly the time before and after the loop is
O
(1), and the loop body
takes
O
(1) time per iteration.
Question: How many loop iterations are there? Clearly, this depends on
the gap between “hi” and “lo”. We can write a
recurrence
for the
number of loop iterations
L
(
n
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '10
 fleck
 Binary Search, Sort, Insertion Sort, Big O notation, array a1

Click to edit the document details