Upload
adele-parks
View
239
Download
0
Embed Size (px)
Citation preview
Algorithms
Java MethodsA & AB
Object-Oriented Programmingand Data Structures
Maria Litvin ● Gary Litvin
Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
chapter 4
4-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
4-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)
4-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
4-5
Example: calculate 12 + 22 + ... + n2
• Pseudocode
Input: n
sum 0i 1Repeat the followingthree steps while i n: sq i * i sum sum + sq i i + 1
Output: sum
A B
Set A to the value of B
4-6
Example (cont’d)
• Flowchart
n
sum 0i 1
i n ?
sq i * isum sum + sqi i + 1
sum
No
Yes
Input / output
Processing step
Decision
4-7
Another Example:
1. Start at pos0, facing dir02. If wall in front, turn 90º clockwise else go forward3. If not back to initial position / direction proceed to Step 2 else stop
dir dir + 90º
pos = pos0and dir = dir0?
YesNo
Yes
No
pos pos0 dir dir0
Step forward
Input:pos0, dir0
Stop
Wall in front?
4-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 sum + sq
sum
4-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)
4-10
Properties (cont’d)
Input: n
sum 0i 1Repeat the followingthree steps while i n: sq i * i sum sum + sq i i + 1
Output: sum
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)
General: works for any n
4-11
Properties (cont’d)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; end;
Abstract:PascalC/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; }}
int addSquares(int n){ int i, sum = 0; for (i = 1; i <= n; i++) sum += i * i; return sum;}
4-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
4-13
Iterations: while Loop in Java
For example:
while (<this condition holds>) { ... // do something }
while (i <= n) { sum += i * i; // add i * i to sum i++; // increment i by 1 }
4-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 ( int i = 1; i <= n; i++) { sum += i * i; // add i * i to sum }
For example: Increment i by 1
4-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.
4-16
Recursion: an ExampleProcedure: Climb steps
Base case: if no steps to climb stop
Recursive case: more steps to climb 1. Step up one step
2. Climb steps
4-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
Calls itself (with a smaller value of the parameter)
4-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
addSquares (4)
addSquares (3)
addSquares (2)
addSquares (1)
addSquares (0)
3
2
0
1
0
1
5
14
Base case
4 30
4-19
Recursion (cont’d)Recursion is especially useful for dealing with nested structures or branching processes
4-20
Recursion (cont’d)
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
(This is pseudocode, not Java!)
4-21
Euclid’s Algorithm• Finds the greatest common factor (GCF) of
two positive integers• Circa 300 BC
4-22
Euclid’s Algorithm (cont’d)
a, b
a = b?
a > b?
a a - b b b - a
a
Yes
Yes No
No
4-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
4-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
Amy
5
Ben
3
Cal
2
Dan
0
Eve
6
In Java, the elements are counted from 0
Fay
1
Guy
4
4-25
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 1
Java’s “for each” loop (a.k.a. enhanced for loop)
4-26
Sequential Search
• The number of comparisons is proportional to n, where n is the length of the list
Amy
5
Ben
3
Cal
2
Dan
0
Eve
6
Fay
1
Guy
4
Amy? Amy? Amy? Amy? Amy? Amy!
4-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
4-28
Binary Search (cont’d)
Fay
5
Dan
3
Cal
2
Amy
0
Guy
6
Ben
1
Eve
4
Eve?
Fay
5
Dan
3
Cal
2
Amy
0
Guy
6
Ben
1
Eve
4
Fay
5
Dan
3
Cal
2
Amy
0
Guy
6
Ben
1
Eve
4
Eve?
Eve!
4-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
4-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?
4-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?