DS Chapter 03
DS Chapter 03
Chapter 3
The Fundamentals: Algorithms, the
Integers, and Matrices
search interval
a c d f g h j l m o p r s u v x z
center element
search interval
a c d f g h j l m o p r s u v x z
center element
search interval
a c d f g h j l m o p r s u v x z
center element
search interval
a c d f g h j l m o p r s u v x z
center element
search interval
a c d f g h j l m o p r s u v x z
center element
found !
01/31/24 Discrete Mathematics Chapter 3 12
Algorithm Examples
procedure binary_search(x: integer; a1, a2, …, an:
integers)
i := 1 {i is left endpoint of search interval}
j := n {j is right endpoint of search interval}
while (i < j)
begin
m := (i + j)/2
if x > am then i := m + 1
else j := m
end
if x = ai then location := i
else location := 0
{location is the subscript of the term that equals x, or is
zero if x is not found}
01/31/24 Discrete Mathematics Chapter 3 13
Algorithm Examples
Sorting:
Use the bubble sort to put 3, 2, 4, 1, 5 into increasing
order.
f(x) is O(x2).