csc 205 – java programming ii lecture 22 march 1, 2002
TRANSCRIPT
CSC 205 – Java Programming II
Lecture 22March 1, 2002
User’s v.s. Developer’s Views
• User’s view– A better name could be client or external view– A user or client of an object o shouldn’t be
bothered with the implementation details of o • How does o store its state?
• How does o perform an action?
• Developer’s view– A better name could be internal view
Client of Server Roles
Program that uses collection
addremovesize
contains
Client object(e.g. a MyMusic object)
Server object(e.g. the LinkedCollection object)
Entities
Why Do We Need Abstraction
Using Collection Objects
cd1 cd2 null
cassette1 null
0
1
musics:Linked
Collection
MyMusics
aTitle1
cassette2
musics[0]:LinkedCollection
musics[1]:LinkedCollection
m:Music
Add a Music object m musics[m.getType()].add(m);
Remove a Music object m musics[m.getType()].remove(m);
Internal View
YESNO
MAYBE
head
newEntry
null
null
Add a new entry newEntry newEntry.next = head; head = newEntry;
The equals Method
prublic boolean equals (Object o)
{
if ( !(o instance of Date) )
return false;
else
Date d = (Date) o;
return (year==d.getYear() &&
month==d.getMonth() &&
day==d.getDay());
}
Big O Notations
• A rough estimation of how fast a function f(n) increase with the growth of n
• The hierarchy of orders O(1)O(log2n)O(n)O(n log2n)O(n 2 )… O(2 n )
• When n = 1,000,000– log2n ~ 20– n = 1,000,000– n log2n ~ 20,000,000– n 2 = 1,000,000,000,000
The Smallest Upper Bound
• Question 4(a)– Expand the expression
f(n) = (2+n)(3+log2n) = 6+2log2n+3n+n log2n– Find the highest order term
n log2n O(n log2n)– Use definition
f(n) <= C n log2n, when n >= K In this case K = 8, C = 4.
Show Equivalency
• Question 4(b)– Use definition f(n) is O(n+7) means f(n) <= C(n +7), when n >= K– Substitute C(n +7) = Cn +7C <= (C+7) n, when n >= C– Proved f(n) <= C’n , when n >= K’ f(n) is O(n) where C’ = C+7, K’ = C
Recursion
private static int puzzle (int n)
{
if ( (n % 3) == 2 )
return 1; //base case
else if ( (n % 3) == 1 )
return ( puzzle (n + 1) + 2 );
else
return ( puzzle (n / 3) + 1 );
}
Tracing Recursive Processespuzzle(9)LV: n=9RA: returnpuzzle(3)+1
puzzle(3)LV: n=3RA: returnpuzzle(2)+1
puzzle(2)LV: n=2RA: returnpuzzle(1)+1
puzzle(1)
return 1
Push execution state in stack: Local Variables Return Address
Pop execution state from stack: Local Variables Return Address
Towers of Hanoi
Algorithm
move (n, orig, dest, temp) { if (n == 1) Move disk from orig to dest; else { move (n - 1, orig, temp, dest); move (1, orig, dest, temp); move (n - 1, temp, dest, orig) ; } // else}
Tracing Recursive Processes