2005/Sep/19 1
Homework #2 Chapter 1: Exercises 7, 9 with modifications: for Exercise 7.a: 20 and 32 are changed as your ID number s last two digits and 60. for Exercise 9: 47x25 are change as 47x(your ID number s last two digits. Chapter 2: If (your ID number s last two digits % 6) = 1: 1, 7, 13 If (your ID number s last two digits % 6) = 2: 2, 8, 14 If (your ID number s last two digits % 6) = 0: 6, 12, 18 2
The Definition of Computer Science Algorithm Dictionary definition (continued) Procedure for solving a mathematical problem in a finite number of steps that frequently involves repetition of an operation A step-by-step method for accomplishing a task Informal description An ordered sequence of instructions that is guaranteed to solve a specific problem 3
The Definition of Computer Science (continued) An algorithm is a list that looks like STEP 1: Do something STEP 2: Do something STEP 3: Do something...... STEP N: Stop, you are finished 4
The Definition of Computer Science (continued) Categories of operations used to construct algorithms Sequential operations Carries out a single well-defined task; when that task is finished, the algorithm moves on to the next operation Conditional operations Ask a question and then select the next operation to be executed on the basis of the answer to that question Iterative operations Tell us to go back and repeat the execution of a previous block of instructions 5
The Definition of Computer Science (continued) Algorithm for Adding Two m-digit Numbers Given : m 1and two positive numbers each containing m digits, a and b Wanted : c Setp 4 Setp 5 m 1 b m 2 m b c m 1 0 c m 2 c, where c steps 4 through 6. Add the two digits ai and bi If c 10, then reset c to Setp 8 Print out the final answer, c Setp 9 Stop. 0 m 2 c 10 otherwise, set the new value of carry to 0. Setp 6 Add1 to i, effectively moving one column to the left. Setp 7 Set c to the value of carry. c m 1 a a a b b b Algorithm : Step1 Set the value of carry to 0. Setp 2 Set the value of i to 0. Setp 3 While the value of i is less than or equal to m 1, repeat the instructions in m i m i m c c i m 1 to the current value of carry to get ci. and reset the value of carry to1; c c m 2 0 c 0. m 1 m 2 0 m 1 a m 2 m 1 a m 2 0 0 6
The Definition of Computer Science (continued) If we can specify an algorithm to solve a problem, we can automate its solution Computing agent: The machine, robot, person, or thing carrying out the steps of the algorithm Does not need to understand the concepts or ideas underlying the solution 7
The Formal Definition of an Algorithm Algorithm A well-ordered collection of unambiguous and effectively computable operations that, when executed, produces a result and halts in a finite amount of time Unambiguous operation An operation that can be understood and carried out directly by the computing agent without needing to be further simplified or explained 8
The Formal Definition of an Algorithm (continued) A primitive operation (or a primitive) of the computing agent Operation that is unambiguous for computing agent Primitive operations of different individuals (or machines) vary An algorithm must be composed entirely of primitives Effectively computable Computational process exists that allows computing agent to complete that operation successfully 9
The Formal Definition of an Algorithm (continued) The result of the algorithm must be produced after the execution of a finite number of operations Infinite loop The algorithm has no provisions to terminate A common error in the designing of algorithms 10
The Importance of Algorithmic Problem Solving Algorithmic solutions can be: Encoded into some appropriate language Given to a computing agent to execute The computing agent Would mechanically follow these instructions and successfully complete the task specified Would not have to understand Creative processes that went into discovery of solution Principles and concepts that underlie the problem 11
Summary Computer science is the study of algorithms An algorithm is a well-ordered collection of unambiguous and effectively computable operations that, when executed, produces a result and halts in a finite amount of time If we can specify an algorithm to solve a problem, then we can automate its solution Computers developed from mechanical calculating devices to modern electronic marvels of miniaturization 12
Chapter 2: Algorithm Discovery and Design Objectives In this chapter, you will learn about: Representing algorithms Examples of algorithmic problem solving 13
Introduction This chapter discusses algorithms and algorithmic problem solving using three problems: Searching lists Finding maxima and minima Matching patterns 14
Representing Algorithms Natural language Language spoken and written in everyday life Examples: English, Spanish, Arabic, etc. Problems with using natural language for algorithms Verbose Imprecise Relies on context and experiences to give precise meaning to a word or phrase 15
Representing Algorithms Figure 2.1 The Addition Algorithm of Figure 1.2 Expressed in Natural Language 16
Representing Algorithms High-level programming language Examples: C++, Java Problem with using a high-level programming language for algorithms During the initial phases of design, we are forced to deal with detailed language issues 17
Representing Algorithms Figure 2.2 The Beginning of the Addition Algorithm of Figure 1.2 Expressed in a High- Level Programming Language 18
Pseudocode English language constructs modeled to look like statements available in most programming languages Steps presented in a structured manner (numbered, indented, etc.) No fixed syntax for most operations is required 19
Pseudocode (continued) Less ambiguous and more readable than natural language Emphasis is on process, not notation Well-understood forms allow logical reasoning about algorithm behavior Can be easily translated into a programming language 20
Sequential Operations Types of algorithmic operations Sequential Conditional Iterative 21
Sequential Operations (continued) Computation operations Example Set the value of variable to arithmetic expression Variable Named storage location that can hold a data value 22
Sequential Operations (continued) Input operations To receive data values from the outside world Example Get a value for r, the radius of the circle Output operations To send results to the outside world for display Example Print the value of Area 23
Sequential Operations (continued) Figure 2.3 Algorithm for Computing Average Miles per Gallon 24
Conditional and Iterative Operations Sequential algorithm Also called straight-line algorithm Executes its instructions in a straight line from top to bottom and then stops Control operations Conditional operations Iterative operations 25
Conditional and Iterative Operations Conditional operations (continued) Ask questions and choose alternative actions based on the answers Example if x is greater than 25 then else print x print x times 100 26
Conditional and Iterative Operations Iterative operations (continued) Perform looping behavior; repeating actions until a continuation condition becomes false Loop The repetition of a block of instructions 27
Conditional and Iterative Operations Examples while j > 0 do set s to s + a j set j to j -1 (continued) repeat print a k set k to k + 1 until k > n 28
Figure 2.4 Second Version of the Average Miles per Gallon Algorithm 29
Conditional and Iterative Operations (continued) Components of a loop Continuation condition Loop body Infinite loop The continuation condition never becomes false An error 30
Figure 2.5 Third Version of the Average Miles per Gallon Algorithm 31
Conditional and Iterative Operations Pretest loop (continued) Continuation condition tested at the beginning of each pass through the loop It is possible for the loop body to never be executed While loop 32
Conditional and Iterative Operations Posttest loop (continued) Continuation condition tested at the end of loop body Loop body must be executed at least once Do/While loop 33
Figure 2.6 Summary of Pseudocode Language Instructions 34
Example 1: Looking, Looking, Looking Examples of algorithmic problem solving Sequential search: find a particular value in an unordered collection Find maximum: find the largest value in a collection of data Pattern matching: determine if and where a particular pattern occurs in a piece of text 35
Example 1: Looking, Looking, Looking (continued) Task Find a particular person s name from an unordered list of telephone subscribers Algorithm outline Start with the first entry and check its name, then repeat the process for all entries 36
Example 1: Looking, Looking, Algorithm discovery Looking (continued) Finding a solution to a given problem Naïve sequential search algorithm For each entry, write a separate section of the algorithm that checks for a match Problems Only works for collections of exactly one size Duplicates the same operations over and over 37
Example 1: Looking, Looking, Looking (continued) Correct sequential search algorithm Uses iteration to simplify the task Refers to a value in the list using an index (or pointer) Handles special cases (like a name not found in the collection) Uses the variable Found to exit the iteration as soon as a match is found 38
Figure 2.9 The Sequential Search Algorithm 39
Example 1: Looking, Looking, Looking (continued) The selection of an algorithm to solve a problem is greatly influenced by the way the data for that problem are organized 40
Example 2: Big, Bigger, Biggest Task Find the largest value from a list of values Algorithm outline Keep track of the largest value seen so far (initialized to be the first in the list) Compare each value to the largest seen so far, and keep the larger as the new largest 41
Example 2: Big, Bigger, Biggest (continued) Once an algorithm has been developed, it may itself be used in the construction of other, more complex algorithms Library A collection of useful algorithms An important tool in algorithm design and development 42
Example 2: Big, Bigger, Biggest Find Largest algorithm (continued) Uses iteration and indices like previous example Updates location and largest so far when needed in the loop 43
Figure 2.10 Algorithm to Find the Largest Value in a List 44
Example 3: Meeting Your Match Task Find if and where a pattern string occurs within a longer piece of text Algorithm outline Try each possible location of pattern string in turn At each location, compare pattern characters against string characters 45
Example 3: Meeting Your Match Abstraction (continued) Separating high-level view from low-level details Key concept in computer science Makes difficult problems intellectually manageable Allows piece-by-piece development of algorithms 46
Example 3: Meeting Your Match Top-down design (continued) When solving a complex problem: Create high-level operations in first draft of an algorithm After drafting the outline of the algorithm, return to the high-level operations and elaborate each one Repeat until all operations are primitives 47
Example 3: Meeting Your Match (continued) Pattern-matching algorithm Contains a loop within a loop External loop iterates through possible locations of matches to pattern Internal loop iterates through corresponding characters of pattern and string to evaluate match 48
Figure 2.12 Final Draft of the Pattern-Matching Algorithm 49
Summary Algorithm design is a first step in developing an algorithm Must also: Ensure the algorithm is correct Ensure the algorithm is sufficiently efficient Pseudocode is used to design and represent algorithms 50
Summary Pseudocode is readable, unambiguous, and analyzable Algorithm design is a creative process; uses multiple drafts and top-down design to develop the best solution Abstraction is a key tool for good design 51