Chapter 07
Chapter 07
Problem Solving
and Algorithms
Chapter Goals
2
Chapter Goals
3
Problem Solving
Problem solving
The act of finding a solution to a perplexing,
distressing, vexing, or unsettled question
4
Problem Solving
5
Problem Solving
Ask questions!
– What do I know about the problem?
– What is the information that I have to process
in order the find the solution?
– What does the solution look like?
– What sort of special cases exist?
– How will I recognize that I have found
the solution?
7
Strategies
9
Computer Problem-Solving
10
Phase Interactions
Should we
add another
arrow?
(What happens
if the problem
is revised?)
11
Algorithms
Algorithm
A set of unambiguous instructions for solving a
problem or subproblem in a finite amount of time
using a finite amount of data
Abstract Step
An algorithmic step containing unspecified details
Concrete Step
An algorithm step in which all details are specified
12
Developing an Algorithm
13
Summary of Methodology
14
Top-Down Design
Control structure
An instruction that determines the order in
which other instructions in a program are
executed
Can you name the ones we defined in the
functionality of pseudocode?
16
Selection Statements
Flow of control of
if statement
17
Algorithm with Selection
18
Algorithm with Selection
Determine Dress
IF (temperature > 90)
Write “Texas weather: wear shorts”
ELSE IF (temperature > 70)
Write “Ideal weather: short sleeves are fine”
ELSE IF (temperature > 50)
Write “A little chilly: wear a light jacket”
ELSE IF (temperature > 32)
Write “Philadelphia weather: wear a heavy coat”
ELSE
Write “Stay inside”
19
Looping Statements
20
Looping Statements
A count-controlled loop
Set sum to 0
Set count to 1
While (count <= limit)
Read number
Set sum to sum + number Why is it
Increment count called a
Write "Sum is " + sum count-controlled
loop?
21
Looping Statements
An event-controlled loop
Set sum to 0
Set allPositive to true
WHILE (allPositive) Why is it
Read number called an
IF (number > 0) event-conrolled
Set sum to sum + number loop?
ELSE What is the
Set allPositive to false event?
Write "Sum is " + sum
22
Looping Statements
Read in square
Calculate the square root
Write out square and the square root
23
Looping Statements
Set epsilon to 1
WHILE (epsilon > 0.001)
Calculate new guess
Set epsilon to abs(square - guess * guess)
24
Looping Statements
Set newGuess to
(guess + (square/guess)) / 2.0
25
Looping Statements
Read in square
Set guess to square/4
Set epsilon to 1
WHILE (epsilon > 0.001)
Calculate new guess
Set epsilon to abs(square - guess * guess)
Write out square and the guess
26
Composite Data Types
Records
A named heterogeneous collection of items in
which individual items are accessed by name. For
example, we could bundle name, age and hourly
wage items into a record named Employee
Arrays
A named homogeneous collection of items in
which an individual item is accessed by its position
(index) within the collection
27
Composite Data Types
Employee
name
age
hourly/Wage
Following algorithm, stores values into the fields of record:
numbers[0]
Insert 7.5
numbers[4]
29
Arrays
30
An Unsorted Array
data[0]...data[length-1]
is of interest
31
Composite Data Types
Fill an array numbers with limit values
integer data[20]
Write “How many values?”
Read length
Set index to 0
WHILE (index < length)
Read data[index]
Set index to index + 1
32
Sequential Search of an
Unsorted Array
A sequential search examines each item in turn
and compares it to the one we are searching.
If it matches, we have found the item. If not, we
look at the next item in the array.
We stop either when we have found the item or
when we have looked at all the items and not
found a match
Thus, a loop with two ending conditions
33
Sequential Search Algorithm
Set Position to 0
Set found to FALSE
WHILE (position < length AND NOT found )
IF (numbers [position] equals searchitem)
Set Found to TRUE
ELSE
Set position to position + 1
34
Booleans
Boolean Operators
A Bolean variable is a location in memory that can contain
either true or false
Boolean operator AND returns TRUE if both operands are
true and FALSE otherwise
Boolean operator OR returns TRUE if either operand is true
and FALSE otherwise
Boolean operator NOT returns TRUE if its operand is false
and FALSE if its operand is true
35
Sorted Arrays
•The values stored in an array have unique keys of a
type for which the relational operators are defined.
36
Sequential Search in a Sorted
Array
Is this better?
37
A Sorted Array
A sorted array of
integers
38
A Sorted Array
39
A Sorted Array
Sequential search
Search begins at the beginning of the list and
continues until the item is found or the entire list
has been searched
Binary search (list must be sorted)
Search begins at the middle and finds the item or
eliminates half of the unexamined items; process
is repeated on the half where the item might be
Say that again…
41
Binary Search
Set first to 0
Set last to length-1
Set found to FALSE
WHILE (first <= last AND NOT found)
Set middle to (first + last)/ 2
IF (item equals data[middle]))
Set found to TRUE
ELSE
IF (item < data[middle])
Set last to middle – 1
ELSE
Set first to middle + 1
RETURN found
42
Binary Search
43
Figure 7.10 Trace of the binary search
Binary Search
Sorting
Arranging items in a collection so that there is an
ordering on one (or more) of the fields in the items
Sort Key
The field (or fields) on which the ordering is based
Sorting algorithms
Algorithms that order the items in the collection
based on the sort key
Why is sorting important?
45
Selection Sort
46
Selection Sort
47
Selection Sort
48
Selection Sort
Selection Sort
Set firstUnsorted to 0
WHILE (not sorted yet)
Find smallest unsorted item
Swap firstUnsorted item with the smallest
Set firstUnsorted to firstUnsorted + 1
49
Selection Sort
50
Selection Sort
51
Bubble Sort
53
Bubble Sort
54
Bubble Sort
Bubble Sort
Set firstUnsorted to 0
Set index to firstUnsorted + 1
Set swap to TRUE
WHILE (index < length AND swap)
Set swap to FALSE
“Bubble up” the smallest item in unsorted part
Set firstUnsorted to firstUnsorted + 1
55
Bubble Sort
Bubble up
Set index to length – 1
WHILE (index > firstUnsorted + 1)
IF (data[index] < data[index – 1])
Swap data[index] and data[index – 1]
Set swap to TRUE
Set index to index - 1
56
Insertion Sort
58
Insertion Sort
InsertionSort
Set current to 1
WHILE (current < length)
Set index to current
Set placeFound to FALSE
WHILE (index > 0 AND NOT placeFound)
IF (data[index] < data[index – 1])
Swap data[index] and data[index – 1]
Set index to index – 1
ELSE
Set placeFound to TRUE
Set current to current + 1
59
Subprogram Statements
Remember?
60
Subprogram Statements
What if the subprogram needs data from the
calling unit?
Parameters
Identifiers listed in parentheses beside the
subprogram declaration; sometimes called formal
parameters
Arguments
Identifiers listed in parentheses on the
subprogram call; sometimes called actual
parameters
61
Subprogram Statements
63
Recursion
Recursion
The ability of a subprogram to call itself
Base case
The case to which we have an answer
General case
The case that expresses the solution in terms of a
call to itself with a smaller version of the problem
64
Recursion
65
Recursion
Write “Enter n”
Read n
Set result to Factorial(n)
Write result + “ is the factorial of “ + n
Factorial(n)
IF (n equals 0)
RETURN 1
ELSE
RETURN n * Factorial(n-1)
66
Recursion
Quicksort(first, last)
IF (first < last) // There is more than one item
Select splitVal
Split (splitVal) // Array between first and
// splitPoint–1 <= splitVal
// data[splitPoint] = splitVal
// Array between splitPoint + 1
// and last > splitVal
Quicksort (first, splitPoint - 1)
Quicksort (splitPoint + 1, last)
70
Quicksort
71
Quicksort
Split(splitVal)
Set left to first + 1
Set right to last
WHILE (left <= right)
Increment left until data[left] > splitVal OR left > right
Decrement right until data[right] < splitVal
OR left > right
IF(left < right)
Swap data[left] and data[right]
Set splitPoint to right
Swap data[first] and data[splitPoint]
Return splitPoint
72
Quicksort
73
Important Threads
Information Hiding
The practice of hiding the details of a module with
the goal of controlling access to it
Abstraction
A model of a complex system that includes only
the details essential to the viewer
Data abstraction
Separation of the logical view of data from their
implementation
Procedural abstraction
Separation of the logical view of actions from their
implementation
Control abstraction
Separation of the logical view of a control structure from its
implementation
75
Important Threads
Identifiers
Names given to data and actions, by which
– we access the data and
Read firstName, Set count to count + 1
– execute the actions
Split(splitVal)
78
Who am I?
79
Who am I?
I am a
mathematician.
Why is my
picture in a
book about
computer
science?
80
Do you know?
81