ICS141: Discrete Mathematics For Computer Science I
ICS141: Discrete Mathematics For Computer Science I
ICS141:
Discrete Mathematics for
Computer Science I
Dept. Information & Computer Sci., University of Hawaii
Jan Stelovsky
based on slides by Dr. Baek and Dr. Still
Originals by Dr. M. P. Frank and Dr. J.L. Gross
Provided by McGraw-Hill
Lecture 14
Chapter 3. The Fundamentals
3.1 Algorithms
n Previously…
n Characteristics of algorithms
n Pseudocode
n Today…
n Examples: Sum algorithm
n Problem of searching an ordered list
n Linear search & binary search algorithms
n Sorting problem
n Bubble sort & insertion sort algorithms
ICS 141: Discrete Mathematics I – Fall 2011 13-3
Practice Exercises
University of Hawaii
procedure binary_search
(x: integer, a1, a2, …, an: increasing integers)
i := 1 {left endpoint of search interval}
j := n {right endpoint of search interval}
while i < j begin {while interval has > 1 item}
m := ⎣(i + j)/2⎦ {midpoint}
if x > am then i := m + 1 else j := m
end
if x = ai then location := i else location := 0
return location {index or 0 if not found}
ICS 141: Discrete Mathematics I – Fall 2011 13-8
Search Example
University of Hawaii
procedure bubble_sort
(a1, a2, …, an: real numbers, n ≥ 2)
for i := 1 to n – 1 {iterate n – 1 passes}
for j := 1 to n – i
if aj > aj+1 then interchange aj and aj+1
{an-i+1, …, an is sorted and ≤ a1, …, an-i}
{a1, a2, …, an is sorted}
procedure insertion_sort
(a1, a2, …, an: real numbers, n ≥ 2)
for i := 2 to n begin
m := ai {the element to be inserted}
j := 1
while aj < m {look for the index of the hole with j }
j := j + 1
{now a1, …, aj-1 < m ≤ aj, …, ai }
{the hole is at j; j ≤ i, i.e. possibly j = i }
for k := j + 1 to i
ak := ak+1
ai := m
{a1, a2, …, ai are sorted in increasing order}
end {a1, a2, …, an are sorted in increasing order}