Download presentation
Presentation is loading. Please wait.
Published byWidya Tan Modified over 6 years ago
1
Java Methods chapter 4 Algorithms A & AB Object-Oriented Programming
and Data Structures Maria Litvin ● Gary Litvin chapter 4 Too often students want to jump to writing code without the necessary background in algorithms. Algorithms Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
2
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 Much more on recursion in Chapter 22.
3
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) Fundamental concepts are often hard to define!
4
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 In pseudocode and flowcharts we do not use data types for variables (such as int, double, etc.); in Java we do.
5
Example: calculate 12 + 22 + ... + n2
Pseudocode Input: n sum 0 i 1 Repeat the following three steps while i n: sq i * i sum sum + sq i i + 1 Output: sum A B Set A to the value of B The “repeat” statement is what makes this algorithm compact.
6
Example (cont’d) Flowchart n Input / output sum 0 i 1
Processing step No Decision i n ? Yes Flowcharts are pretty much history: they are really not used in software development any more since programming has switched to OOP. sq i * i sum sum + sq i i + 1 sum
7
Another Example: Input: pos0, dir0 pos pos0 dir dir0 No
1. Start at pos0, facing dir0 2. If wall in front, turn 90º clockwise else go forward 3. If not back to initial position / direction proceed to Step 2 stop pos pos0 dir dir0 No Wall in front? Yes Step forward dir dir + 90º One should specify when a given algorithm applies (preconditions) and its final state (postconditions). What are the preconditions here? The room is rectangular; the robot is placed next to a wall. What if the preconditions aren’t satisfied? Infinite loop, the program “hangs.” pos = pos0 and dir = dir0? No Yes Stop
8
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 So “variable” here is not the same as “variable” in algebra. sum sum + sq
9
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) Iterations and recursion make an algorithm different from a cookbook recipe. In most cookbook instructions, each step is performed once. This works because the chef is slow. But a computer is very fast, billions of times faster than a programmer. If we had to write out separately every instruction that a computer executes, we wouldn’t be able to take advantage of its speed. In non-trivial algorithms, the same sequences of steps are repeated multiple times (but the values of variables are updated at each step).
10
Properties (cont’d) Input: n General: works for any n sum 0 i 1
Repeat the following three steps while i n: sq i * i sum sum + sq i i + 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 Thus an algorithm can take input parameters. (The “running time” depends on n, of course)
11
Properties (cont’d) Abstract: Pascal C/C++ Java int addSquares(int n)
{ int i, sum = 0; for (i = 1; i <= n; i++) sum += i * i; return sum; } function addSquares(n : integer) : integer; var i, sum : integer; begin sum := 0; for i := 1 to n do begin sum := sum + i * i end; addSquares := sum; Abstract: Pascal C/C++ Java public class MyMath { public static int addSquares(int n) int sum = 0; for (int i = 1; i <= n; i++) sum += i * i; return sum; } Algorithms depend on a particular computational model. An algorithm for abacus will be different from an algorithm for computer, and an algorithm for parallel computer may be different from an algorithm for conventional von Neumann computer.
12
Iterations Repeat the same sequence of instructions multiple times
Start with initial values of variables Values of some of the variables change in each cycle Stop when the tested condition becomes false Supported by high-level programming languages In iterations, some condition is checked on each cycle to decide whether to continue iterations or to quit.
13
Iterations: while Loop in Java
while (<this condition holds>) { ... // do something } For example: while (i <= n) { sum += i * i; // add i * i to sum i++; // increment i by 1 } When the condition is false, the program quits the loop and goes to the next statement after the loop. If the condition is false at the outset, the loop is skipped altogether.
14
Iterations: for Loop in Java
for (<initial setup>; <as long as this condition holds>; <adjust variable(s) at the end of each iteration>) { ... // do something } For example: Increment i by 1 for ( int i = 1; i <= n; i++) { sum += i * i; // add i * i to sum } for loop is for convenience. It is possible to program everything with while loops.
15
Recursion A recursive solution describes a procedure for a particular task in terms of applying the same procedure to a similar but smaller task. Must have a base case when the task is so simple that no recursion is needed. Recursive calls must eventually converge to a base case. Students who are interested in algorithms may be intrigued by recursion and may try to come up with recursive versions of common algorithms. Others never quite get it.
16
Recursion: an Example Procedure: Climb steps
Base case: if no steps to climb stop Recursive case: more steps to climb 1. Step up one step 2. Climb steps Luckily people can see the big picture; a computer needs step-by-step instructions.
17
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 0 return 0; else return addSquares (n - 1) + n * n; } Base case Some people keep asking: “But how does it work?” The next slide gives a glimpse of it. It may be better to make a leap of faith that the procedure somehow works for n-1 and from that prove that it works for n. Calls itself (with a smaller value of the parameter)
18
Recursion: How Does it Work
Implemented on a computer as a form of iterations, but hidden from the programmer Assisted by the system stack Base case addSquares (0) addSquares (1) 1 1 When a method is called, the system stack holds the return address, method parameters, and local variables. This is explained in more detail in Chapter 22. addSquares (2) 2 5 addSquares (3) 3 14 addSquares (4) 4 30
19
Recursion (cont’d) Recursion is especially useful for dealing with nested structures or branching processes Other examples: trees, graphics pictures that consist of other pictures, game strategies.
20
Recursion (cont’d) (This is pseudocode, not Java!) totalBytes (folder)
{ count 0 for each item X in folder 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 Base case In Java we can introduce a common data type (class) FilingItem with two subclasses, File and Folder. We can define different methods totalSize for a File and a Folder. The correct method will be called automatically for each FilingItem in a folder due to polymorphism.
21
Euclid’s Algorithm Finds the greatest common factor (GCF) of two positive integers Circa 300 BC Euclid wrote Elements, which consists of 13 books. Elements defined the direction of mathematics and the style of mathematical education for over two millennia...
22
Euclid’s Algorithm (cont’d)
a, b Yes a = b? No Yes a > b? No In a quicker version, on each iteration we replace the larger number with the remainder of its division by the smaller number. a a - b b b - a a
23
Euclid’s Algorithm (cont’d)
With iterations With recursion 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; public static int gcf (int a, int b) { if (a == b) // if a equals b return a; if (a > b) return gcf( a - b, b); else // if a < b return gcf(a, b - a); } Base case There are no loops in the recursive version, because recursion replaces iterations.
24
Working with Lists A list is a data structure in which the items are numbered We know how to get to the i-th item We know how to get from one item to the next quickly Dan Fay 1 Cal 2 Ben 3 Guy 4 Amy 5 Eve 6 In Java, the elements are counted from 0 A list can be represented as an array, where the elements stored in consecutive memory locations. A list can be also represented as a linked list, where the elements are scattered in memory, but each element holds a link to (the address of) the next element.
25
List Traversal Start at the first element While more elements remain
process the next element Increment i by 1 for (int i = 0; i < list.length; i++) System.out.println (list [ i ]); We can also traverse a list backward, starting from the end. Java’s “for each” loop (a.k.a. enhanced for loop) for (String word : list) System.out.println (word);
26
Sequential Search Dan Fay 1 Cal 2 Ben 3 Guy 4 Amy 5 Eve 6 Amy? Amy? Amy? Amy? Amy? Amy! The number of comparisons is proportional to n, where n is the length of the list If the value that we are searching for is in the list, it will take, on average, n/2 comparisons to find that value.
27
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 This is the time to play the game “I’m thinking of a number from one to one hundred.” Some teachers prefer to tear an old telephone directory apart.
28
Binary Search (cont’d)
Amy Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve? Amy Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve? This and other simple algorithms (e.g., Selection Sort) can be staged with students. Students should be encouraged to come up with their own examples of “interesting” algorithms. Amy Ben 1 Cal 2 Dan 3 Eve 4 Fay 5 Guy 6 Eve!
29
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 Thus algorithms can be compared for efficiency without implementing them on a computer. For large enough n, Binary Search always overtakes Sequential Search.
30
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? Why algorithms often use iterations? Because a lengthy computation must be described in a relatively small number of instructions. How is pseudocode different from Java code? No rigid syntax, no data types. Name three basic shapes used in flowcharts. Rectangles for calculations, parallelograms for input and output, rhombuses for decisions. Explain how variables are used in iterations. The same instructions are executed, but on different values of variables. Eventually the values of the variables make the condition for continuing iterations false, and the program quits iterations. Which Java statements can be used to express iterations? while, for.
31
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? What is called a base case in recursion? A simple case where the answer or solution can be given without recursive calls. Suppose we define “word” as a sequence of letters. Turn this into a recursive definition. A word is either one letter (base case) or a letter followed by a word. When does Binary Search apply? When the elements of the array are arranged in an ascending or descending order How many comparisons, on average, are needed to find one of the values in a list of 1000 elements using Sequential Search? Binary Search?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.