520 likes | 528 Views
Chapter 5: Algorithms. Computer Science: An Overview Eleventh Edition by J. Glenn Brookshear. Chapter 5: Algorithms. 5.1 The Concept of an Algorithm 5.2 Algorithm Representation 5.3 Algorithm Discovery 5.4 Iterative Structures 5.5 Recursive Structures 5.6 Efficiency and Correctness.
E N D
Chapter 5:Algorithms Computer Science: An OverviewEleventh Edition by J. Glenn Brookshear
Chapter 5: Algorithms • 5.1 The Concept of an Algorithm • 5.2 Algorithm Representation • 5.3 Algorithm Discovery • 5.4 Iterative Structures • 5.5 Recursive Structures • 5.6 Efficiency and Correctness
Definition of Algorithm An algorithm is an ordered set of unambiguous, executable steps that defines a terminating process.
Definition of Algorithm (Cont.) • Ordered: parallel algorithm? Not the first-step, second-step scenario • Executable: make a list of all the positive integers? • Unambiguous: need sufficient information, does not require creative skills • Terminating: the execution must lead to an end (consider the case of “long-division algorithm”)
The Abstract Nature of Algorithms • An algorithm v.s. its representation: a story v.s. a book • The level of detail • F = (9/5)C + 32 • Convert the Celsius reading to its Fahrenheit equivalent” • Programs: representation of algorithms • Processes: the activities of executing algorithms
Algorithm Representation • Traditional natural language (ambiguity) • Visiting grandchildren can be nerve-racking. • The language of pictures • Few readers could successfully follow the directions • Communication problems: not precisely defined or inadequate information
Primitives • Requires well-defined primitives (a well-defined set of building blocks) • A collection of primitives constitutes a programming language. • Each primitive consists of two part: • Syntax: symbolic representation of the primitive • Semantics: the meaning of the primitive • Lower-level v.s. Higher-level primitives
Pseudocode Primitives • Assignment name expression • Conditional selection ifconditionthenaction • Repeated execution whileconditiondoactivity • Procedure procedurename (generic names)
Polya’s Problem Solving Steps • 1. Understand the problem. • 2. Devise a plan for solving the problem. • 3. Carry out the plan. • 4. Evaluate the solution for accuracy and its potential as a tool for solving other problems.
Program Development Steps • 1. Understand the problem. • 2. Get an idea of how an algorithmic procedure might solve the problem. • 3. Formulate the algorithm and represent it as a program. • 4. Evaluate the program for accuracy and its potential as a tool for solving other problems.
Ages of Children Problem • Person A is charged with the task of determining the ages of B’s three children. • B tells A that the product of the children’s ages is 36. • A replies that another clue is required. • B tells A the sum of the children’s ages. • A replies that another clue is needed. • B tells A that the oldest child plays the piano. • A tells B the ages of the three children. • How old are the three children?
Prediction of a race • Before A, B, C, D ran a race they made the following predictions: • A predicted that B would win. • B predicted that D would be last. • C predicted that A would be the third. • D predicted that A’s prediction would be correct. • Only one of these predictions was true, and this was the prediction made by the winner. • In what order did A, B, C, and D finish the race?
Getting a Foot in the Door • Try working the problem backwards • E.g., unfold a completed bird • Solve an easier related problem • Relax some of the problem constraints • Solve pieces of the problem first (bottom up methodology) • E.g, alphabetizing lists of names “Interchange the names David and Alice. Move the name Carol to the position between Alice and David. Move the name Bob to the position between Alice and Carol.”
Getting a Foot in the Door (Cont.) • Stepwise refinement: Divide the problem into smaller problems (top-down methodology) • E.g. the binary search algorithm (On each step, look at the middle element of the remaining list to eliminate half of it, and quickly zero in on the desired element) <x <x <x >x
Iterative Structures • Pretest loop: while (condition) do (loop body) • Posttest loop: repeat (loop body) until(condition)
Figure 5.10 Sorting the list Fred, Alex, Diana, Byron, and Carol alphabetically
Figure 5.11 The insertion sort algorithm expressed in pseudocode
Recursion • The execution of a procedure leads to another execution of the procedure. • Multiple activations of the procedure are formed, all but one of which are waiting for other activations to complete.
Figure 5.12 Applying our strategy to search a list for the entry John
Another recursion example: Tower of Hanoi Example • Problem: Get all disks from peg 1 to peg 2. • Only move 1 disk at a time. • Never set a larger disk on a smaller one. Peg #1 Peg #2 Peg #3
Algorithm Efficiency • Measured as number of instructions executed • Best, worst, and average case analysis • For example: • Sequential search algorithm for 30,000 records: if 10 milliseconds for retrieving and checking each record for its ID#, then total average 150 seconds • Binary search algorithm for 30,000 records: at most 15 entries are retrieved, so 0.15 seconds are required
Figure 5.18 Applying the insertion sort in a worst-case situation • In the best case, n – 1 comparisons for n entries • In the worse case, (1/2)(n^2 – n) comparisons • In the average case, (1/4)(n^2 – n) comparisons
Figure 5.19 Graph of the worst-case analysis of the insertion sort algorithm
Figure 5.20 Graph of the worst-case analysis of the binary search algorithm
The Growth of Functions • For functions over numbers, we often need to know a rough measure of how fast a function grows. • If f(x) is faster growingthan g(x), then f(x) always eventually becomes larger than g(x) in the limit (for large enough values of x). • Useful in engineering for showing that one design scalesbetter or worse than another.
Concept of Order of Growth • We say fA(n)=30n+8is order n, or O(n). It is, at most, roughly proportional to n. • fB(n)=n2+1 is order n2, or O(n2). It is roughly proportional to n2. • Any O(n2) function is faster-growing than any O(n) function. • For large numbers of user records, the O(n2) function will always take more time.
Definition: O(g), at mostorder g Let g be any function RR. • Define “at most order g”, written O(g), to be: {f :RR | c,k: x>k:|f(x)| c|g(x)|}. • “Beyond some point k, function f is at most a constant c times g (i.e., proportional to g).” • “f is at most order g”, or “f is O(g)”, or “f=O(g)” all just mean that fO(g). • Sometimes the phrase “at most” is omitted.
“Big-O” Proof Examples • Show that 30n+8 is O(n). • Show c,k: n>k:30n+8 cn. • Let c=31, k=8. Assume n >k=8. Thencn = 31n = 30n + n > 30n+8, so 30n+8 < cn. • Show that n2+1 is O(n2). • Show c,k: n >k: n2+1 cn2. • Let c=2, k=1. Assume n>1. Then cn2 = 2n2 = n2+n2 > n2+1, or n2+1< cn2.
Definition: (g), exactly order g • If fO(g) and gO(f) then we say “g and f are of the same order” or “f is (exactly) order g” and write f(g). • Another equivalent definition:(g) {f :RR | c1c2k x >k: |c1g(x)||f(x)||c2g(x)| } • “Everywhere beyond some point k, f(x)lies in between two multiples of g(x).”
Definition: (g) , at least order g • (g) = {f | gO(f)}“The functions that are at least orderg.”
Chain Separating Problem • A traveler has a gold chain of seven links. • He must stay at an isolated hotel for seven nights. • The rent each night consists of one link from the chain. • What is the fewest number of links that must be cut so that the traveler can pay the hotel one link of the chain each morning without paying for lodging in advance?
Figure 5.22 Solving the problem with only one cut (Cont.) • First morning: Give the single link. • Second: Retrieve the single link and give the two-link piece. • Third: Give the single link. • Four: Retrieve the three links and give the four-link piece. • Five: Give the single link. • Six: Retrieve the single link and give the two-link piece. • Seven: Give the single link.
Software Verification • Proof of correctness • Assertions • Check if the assertions so established at the end of the program corresponds to the desired output specifications • E.g., loop invariants for the while structure: an assertion at a point in a loop that is true every time that point in the loop is reached. • Check if the loop invariant and termination condition imply the desired output • Testing: use cases
Figure 5.23 The assertions associated with a typical while structure
Consider the insertion sort algorithm again • The loop invariant: Each time the test for termination is performed, the entries in the list from position 1 through position N-1 are sorted. • The termination condition: The value of N is greater than the length of the list.