Chapter 4 - Algorithms. This chapter’s objectives are to: Understand general properties of algorithms, get familiar with pseudocode and flowcharts, learn about iterations and recursion, learn about working with lists, learn basic facts about OOP.
Java Methods Object-Oriented Programming and Data Structures 2nd AP edition with GridWorld Maria Litvin ● Gary Litvin chapter 4 Algorithms Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing All rights reserved Objectives: • • • • • Understand general properties of algorithms Get familiar with pseudocode and flowcharts Learn about iterations and recursion Learn about working with lists Learn basic facts about OOP 42 Define Algorithm • Hard to define formally • A more or less compact, general, and abstract step-by-step recipe that describes how to perform a certain task or solve a certain problem • Examples: Long division Euclid’s Algorithm for finding the greatest common factor (circa 300 BC) Binary Search (guess-the-number game) 43 Tools for Describing Algorithms • Pseudocode A sequence of statements, more precise notation Not a programming language, no formal syntax • Flowcharts Graphical representation of control flow 44 Example: calculate 12 + 22 + + n2 • Pseudocode Input: n sum k Repeat the following three steps while k n: sq k * k sum sum + sq k k+1 A B Set A to the value of B Output: sum 45 Example (cont’d) • Flowchart n sum k No k n? Input / output Processing step Decision Yes sq k * k sum sum + sq k k + sum 46 Another Example: Start at pos0, facing dir0 If wall in front, turn 90º clockwise else go forward If not back to initial position / direction proceed to Step else stop Input: pos0, dir0 pos pos0 dir dir0 No Wall in front? dir 90º Step forward pos = pos0 and dir = dir0? Yes Stop 47 Yes dir + No Variables • Algorithms usually work with variables • A variable is a “named container” • A variable is like a slate on which a value can be written and later erased and replaced with another value sum sum sum + sq 48 Properties of Algorithms • Compactness: an algorithm can use iterations or recursion to repeat the same steps multiple times • Generality: the same algorithm applies to any “size” of task or any input values • Abstractness: an algorithm does not depend on a particular computer language or platform (although it may depend on the general computing model) 49 Properties (cont’d) Input: n sum k Repeat the following three steps while k n: sq k * k sum sum + sq k k+1 Output: sum General: works for any n Compact: the same length regardless of n, thanks to iterations the algorithm repeats the same instructions many times, but with different values of the variables (The “running time” depends on n, of course) 410 Recursive Methods • A recursive method calls itself • Must have a base case (can be implicit) • Example: public class MyMath { public static int addSquares (int n) { if (n == 0) // if n is equal to return 0; else return addSquares (n - 1) + n * n; } } Base case Calls itself (with a smaller value of the parameter) 417 Recursion: How Does it Work • Implemented on a computer as a form of iterations, but hidden from the programmer • Assisted by the system stack addSquares (0) Base case addSquares (1) 1 addSquares (2) addSquares (3) addSquares (4) 14 30 418 Recursion (cont’d) Recursion is especially useful for dealing with nested structures or branching processes 419 Recursion (cont’d) totalBytes (folder) { count (This is pseudocode, not Java!) for each item X in folder { Base case if X is a file count count + the number of bytes in X else (if X is a folder) count count + totalBytes(X) } return count } 420 Euclid’s Algorithm • Finds the greatest common factor (GCF) of two positive integers • Circa 300 BC 421 Euclid’s Algorithm (cont’d) a, b Yes a = b? No Yes a a-b No a > b? b b-a a 422 Euclid’s Algorithm (cont’d) • With iterations public static int gcf (int a, int b) { while (a != b) // a not equal to b { if (a > b) a -= b; // subtract b from a else b -= a; // subtract a from b } return a; } • With recursion public static int gcf (int a, int b) { if (a == b) // if a equals b return a; Base case if (a > b) return gcf( a - b, b); else // if a < b return gcf(a, b - a); } 423 Working with Lists • A list is a data structure in which the items are numbered Dan Fay Cal Ben Guy Amy Eve In Java, the elements are counted from • We know how to get to the i-th item • We know how to get from one item to the next quickly 424 List Traversal Start at the first element While more elements remain process the next element for (int i = 0; i < list.length; i++) System.out.println (list [ i ]); for (String word : list) System.out.println (word); Increment i by Java’s “for each” loop (a.k.a enhanced for loop) 425 Sequential Search Dan Fay Cal Ben Guy Amy Amy? Amy? Amy? Amy? Amy? Amy! Eve • The number of comparisons is proportional to n, where n is the length of the list 426 Binary Search • “Divide and conquer” algorithm • The elements of the list must be arranged in ascending (or descending) order • The target value is always compared with the middle element of the remaining search range 427 Binary Search (cont’d) Amy Ben Cal Dan Eve Fay Guy Eve Fay Guy Eve? Amy Ben Cal Dan Eve? Amy Ben Cal Dan Eve Fay Guy Eve! 428 Search: Sequential Binary • The list can be in random order • The number of comparisons is proportional to n • For a list of 1,000,000 elements takes, on average, 500,000 comparisons • The list must be sorted (e.g., in ascending order) • The number of comparisons is proportional to log2 n • For a list of 1,000,000 elements takes, on average, only 20 comparisons 429 Review: • • • • • Why algorithms often use iterations? How is pseudocode different from Java code? Name three basic shapes used in flowcharts Explain how variables are used in iterations Which Java statements can be used to express iterations? 430 Review (cont’d): • What is called a base case in recursion? • Suppose we define “word” as a sequence of letters Turn this into a recursive definition • When does Binary Search apply? • How many comparisons, on average, are needed to find one of the values in a list of 1000 elements using Sequential Search? Binary Search? 431 ... (guess-the-number game) 4? ?3 Tools for Describing Algorithms • Pseudocode A sequence of statements, more precise notation Not a programming language, no formal syntax • Flowcharts Graphical... addSquares (2) addSquares (3) addSquares (4) 14 30 4? ?18 Recursion (cont’d) Recursion is especially useful for dealing with nested structures or branching processes 4? ?19 Recursion (cont’d) totalBytes... return gcf( a - b, b); else // if a < b return gcf(a, b - a); } 4? ?23 Working with Lists • A list is a data structure in which the items are numbered Dan Fay Cal Ben Guy Amy Eve In Java, the elements