5 Algorithm
5 Algorithm
by
Kai-Lung Hua
Algorithms
5-2
Definition of Algorithm
5-3
Algorithm Representation
5-4
Figure 5.2 Folding a bird from a
square piece of paper
5-5
Figure 5.3 Origami primitives
5-6
Pseudocode Primitives
• Assignment
name expression
• Conditional selection
if condition then action
5-7
Pseudocode Primitives (continued)
• Repeated execution
while condition do activity
• Procedure
procedure name (generic names)
5-8
Figure 5.4 The procedure Greetings
in pseudocode
5-9
Polya’s Problem Solving Steps
5-10
Getting a Foot in the Door
5-11
Ages of Children Problem
5-12
Figure 5.5
5-13
Iterative Structures
• Pretest loop:
while (condition) do
(loop body)
• Posttest loop:
repeat (loop body)
until(condition)
5-14
Figure 5.6 The sequential search
algorithm in pseudocode
5-15
Figure 5.7 Components of repetitive
control
5-16
Figure 5.8 The while loop structure
5-17
Figure 5.9 The repeat loop structure
5-18
Figure 5.10 Sorting the list Fred, Alex,
Diana, Byron, and Carol alphabetically
5-19
Figure 5.11 The insertion sort
algorithm expressed in pseudocode
5-20
Recursion
5-21
Figure 5.12 Applying our strategy to
search a list for the entry John
5-22
Figure 5.13 A first draft of the binary
search technique
5-23
Figure 5.14 The binary search
algorithm in pseudocode
5-24
Figure 5.15
5-25
Figure 5.16
5-26
Figure 5.17
5-27
Algorithm Efficiency
5-28
Figure 5.18 Applying the insertion sort in
a worst-case situation
5-29
Figure 5.19 Graph of the worst-case
analysis of the insertion sort algorithm
5-30
Figure 5.20 Graph of the worst-case
analysis of the binary search algorithm
5-31
Software Verification
• Proof of correctness
– Assertions
• Preconditions
• Loop invariants
• Testing
5-32
Chain Separating Problem
5-33
Figure 5.21 Separating the chain
using only three cuts
5-34
Figure 5.22 Solving the problem with
only one cut
5-35
Figure 5.23 The assertions associated
with a typical while structure
5-36