All Slides PDF Format
All Slides PDF Format
www.cs.utexas.edu/~scottm/cs314/handouts/startup.htm
18
Succeeding in the Course - Concrete
Former student:
– "I really like the boot camp nature of
your course."
do the readings
start on assignments early
get help from the teaching staff when you get stuck on an
assignment
attend lecture and discussion sections
go to the extra study sessions, co-study
participate on the class discussion group
do extra problems - http://tinyurl.com/pnzp28f
study for tests using the old tests
study for tests in groups
ask questions and get help 19
Software
Java - Oracle or OpenJDK, limit ourselves to Java 8
IDE such as IntelliJ or Eclipse
Zoom, used occasionally
A. 24
B. 120
C. 143
D. 286
E. 338
CS 314 Efficiency - Complexity 6
Clicker 3
What is output when method sample is called?
// pre: n >= 0, m >= 0
public static void sample(int n, int m) {
int total = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
total += 5;
System.out.println(total);
}
A. 5 D. nm
B. n * m E. (n * m)5
C. n * m * 5
CS 314 Efficiency - Complexity 7
Example
public int total(int[] values) {
int result = 0;
for (int i = 0; i < values.length; i++)
result += values[i];
return result;
}
No = 5
horizontal axis: N, number of elements in data set
CS 314 Efficiency - Complexity 15
Typical Big O Functions – "Grades"
Function Common Name
N! factorial Running
time grows
2N Exponential 'quickly' with
Nd, d > 3 Polynomial more input.
N3 Cubic
N2 Quadratic
N N N Square root N
N log N N log N
N Linear
Running
N Root - n time grows
'slowly' with
log N Logarithmic
more input.
1 Constant
CS 314 Efficiency - Complexity 16
Clicker 4
Which of the following is true?
Recall T(N)total = 3N + 4
A. Method total is O(N1/2)
B. Method total is O(N)
C. Method total is O(N2)
D. Two of A – C are correct
E. All of three of A – C are correct
red line is
2Nlog10 N + 100000
blue line is
N2/10000
O(N2) ind. 3.4x10-3 1.4x10-3 4.4x10-3 0.22 0.86 3.45 13.79 (55)
O(N2) (27.6)
1.8x10-3 7.1x10-3 2.7x10-2 0.11 0.43 1.73 6.90
dep.
(1745) (13,957) (112k) (896k) (7.2m)
O(N3) 3.40 27.26 (218)
29 min. 233 min 31 hrs 10 days 80 days
O(N3/2) - 1.98 2.48 2.87 2.79 2.76 2.85 2.79 2.82 2.81
O(N3) - 8.03 - - - - - - - -
4.0
3.5
3.0
2.5 N
NlogN
Time
2.0 NsqrtN
N^2
1.5 N^2
1.0
0.5
0.0
0 5000 10000 15000 20000 25000 30000 35000
Value of N
0.20
0.18
0.16
0.14
N
0.12
NlogN
Time
0.10 NsqrtN
N^2
0.08
N^2
0.06
0.04
0.02
0.00
0 5000 10000 15000 20000 25000 30000 35000
Value of N
3.00
2.50
2.00
N
Time
1.50 NlogN
NsqrtN
1.00
0.50
0.00
0 100000 200000 300000 400000 500000 600000
Value of N
0.06
0.05
0.04
N
Time
0.03
NlogN
0.02
0.01
0.00
0 100000 200000 300000 400000 500000 600000
Value of N
0.0020
0.0018
0.0016
0.0014
0.0012
0.0010 N
0.0008
0.0006
0.0004
0.0002
0.0000
0 100000 200000 300000 400000 500000 600000
A. The beginning
B. The end
C. The middle
D. A random location
E. Don’t bother to actually add
CS 314 Encapsulation - Implementing Classes 11
IntList Design
Create a new, empty IntList
new IntList -> []
The above is not code. It is a notation that shows
what the results of operations. [] is an empty list.
add to a list.
[].add(1) -> [1]
[1].add(5) -> [1, 5]
[1, 5].add(4) -> [1, 5, 4]
elements in a list have a definite order and a
position.
– zero based position or 1 based positioning?
CS 314 Encapsulation - Implementing Classes 12
IntList aList = new IntList();
aList.add(42);
aList.add(12);
aList.add(37);
aList
0 1 2 con
[42, 12, 37]
The wall of 42 12 37 0 0 0 0 0 0 0
abstraction. 0 1 2 3 4 5 6 7 8 9
a Random object
All objects of type Die have
access to the class variables implementation
and constants. details not shown
Answer: Inheritance.“
1
Features of OO Programming
Encapsulation
– abstraction, creating new data types
– information hiding
– breaking problem up based on data types
Inheritance
– code reuse
– specialization
– "New code using old code."
CS 314 Inheritance 2
Encapsulation
Create a program to allow people to play the
game Monopoly
– Create classes for money, dice, players, the
bank, the board, chance cards, community chest
cards, pieces, etc.
Some classes use other classes. Are clients
– the board consists of spaces
– a player has properties they own
– a piece has a position
Also referred to as composition
CS 314 Inheritance 3
Inheritance
Another kind of relationship exists between
things in the world and data types in programs
There are properties in Monopoly
– a street is a kind of property
– a railroad is a kind of property
– a utility is a kind of property
CS 314 Inheritance 4
Inheritance
In Monopoly there is the concept of a
Property
All properties have some common traits
– they have a name
– they have a position on the board
– they can be owned by players
– they have a purchase price
But some things are different for each of the
three kinds of property
– How to determine rent when another player
lands on the Property
CS 314 Inheritance 5
What to Do?
If we have a separate class for Street,
Railroad, and Utility there is going to be a lot
of code copied
– hard to maintain
– an anti-pattern
Inheritance is a programming feature to
allow data types to build on pre-existing data
types without repeating code
CS 314 Inheritance 6
Mechanics of Inheritance
1. extends keyword
2. inheritance of instance methods
3. inheritance of instance variables
4. object initialization and constructors
5. calling a parent constructor with super()
6. overriding methods
7. partial overriding, super.parentMethod()
8. inheritance requirement in Java
9. the Object class
10. inheritance hierarchies
CS 314 Inheritance 7
Inheritance in Java
Java is designed to encourage object
oriented programming
all classes, except one, must inherit from
exactly one other class
The Object class is the cosmic super class
– The Object class does not inherit from any other class
– The Object class has several important methods:
toString, equals, hashCode, clone, getClass
implications:
– all classes are descendants of Object
– all classes and thus all objects have a toString,
equals, hashCode, clone, and getClass method
• toString, equals, hashCode, clone normally overridden
CS 314 Inheritance 8
Nomenclature of Inheritance
In Java the extends keyword is used in the
class header to specify which preexisting class
a new class is inheriting from
public class Student extends Person
Person is said to be
– the parent class of Student
– the super class of Student
– the base class of Student
– an ancestor of Student
Student is said to be
– a child class of Person
– a sub class of Person
– a derived class of Person
– a descendant of Person
CS 314 Inheritance 9
Clicker 1
What is the primary reason for using
inheritance when programming?
CS 314 Inheritance 10
Clicker 2
What is output when the main method is run?
public class Foo {
public static void main(String[] args) {
Foo f1 = new Foo();
System.out.println(f1.toString());
}
}
A. 0
B. null
C. Unknown until code is actually run.
D. No output due to a syntax error.
E. No output due to a runtime error. 11
Overriding methods
any method that is not final may be
overridden by a descendant class
same signature as method in ancestor
may not reduce visibility
may use the original method if simply want to
add more behavior to existing
– super.originalMethod()
CS 314 Inheritance 12
Constructors
Constructors handle initialization of objects
When creating an object with one or more ancestors (every
type except Object) a chain of constructor calls takes place
The reserved word super may be used in a constructor to
call a one of the parent's constructors
– must be first line of constructor
if no parent constructor is explicitly called the default, 0
parameter constructor of the parent is called
– if no default constructor exists a syntax error results
If a parent constructor is called another constructor in the
same class may no be called
– no super();this(); allowed. One or the other, not both
– good place for an initialization method
CS 314 Inheritance 13
The Keyword super
super is used to access something (any protected or
public field or method) from the super class that has
been overridden
Rectangle's toString makes use of the toString in
ClosedShape my calling super.toString()
without the super calling toString would result in
infinite recursive calls
Java does not allow nested supers
super.super.toString()
results in a syntax error even though technically this
refers to a valid method, Object's toString
Rectangle partially overrides ClosedShapes toString
CS 314 Inheritance 14
Creating a SortedIntList
- A Cautionary Tale
of Inheritance
A New Class
Assume we want to have a list of ints, but
that the ints must always be maintained in
ascending order
[-7, 12, 37, 212, 212, 313, 313, 500]
sortedList.get(0) returns the min
sortedList.get(list.size() – 1)
returns the max
CS 314 Inheritance 16
Implementing SortedIntList
Do we have to write a whole new class?
Assume we have an IntList class.
Clicker 3 - Which of the following methods
have to be changed?
A. add(int value)
B. int get(int location)
C. String toString()
D. int remove(int location)
E. More than one of A – D.
CS 314 Inheritance 17
Overriding the add Method
First attempt
Problem?
solving with insert method
– double edged sort
solving with protected
– What protected really means
CS 314 Inheritance 18
Clicker 4
public class IntList {
private int size
private int[] con
}
public class SortedIntList extends IntList {
public SortedIntList() {
System.out.println(size); // Output?
}
}
A. 0
B. null
C. unknown until code is run
D. no output due to a compile error
E. no output due to a runtime error 19
Problems
What about this method?
void insert(int location, int val)
What about this method?
void insertAll(int location,
IntList otherList)
SortedIntList is not a good application
of inheritance given all the behaviors
IntList provides.
CS 314 Inheritance 20
More Example Code
CS 314 Inheritance 21
Simple Code Example
Create a class named Shape
– what class does Shape inherit from
– what methods can we call on Shape objects?
– add instance variables for a position
– override the toString method
Create a Circle class that extends Shape
– add instance variable for radius
– debug and look at contents
– try to access instance var from Shape
– constructor calls
– use of key word super
CS 314 Inheritance 22
Shape Classes
Declare a class called ClosedShape
– assume all shapes have x and y coordinates
– override Object's version of toString
Possible sub classes of ClosedShape
– Rectangle
– Circle
– Ellipse
– Square
Possible hierarchy
ClosedShape <- Rectangle <- Square
CS 314 Inheritance 23
A ClosedShape class
public class ClosedShape {
public ClosedShape() {
this(0,0);
}
public Rectangle() {
this(0, 0);
}
public Rectangle() {
init(0, 0);
}
CS 314 Inheritance 28
The Real Picture
Fields from Object class
Instance variables
declared in Object
Fields from ClosedShape class
A
Rectangle Instance Variables declared in
object ClosedShape
Available
methods
Fields from Rectangle class
are all methods
from Object, Instance Variables declared in
ClosedShape,
and Rectangle
Rectangle
CS 314 Inheritance 29
Access Modifiers and
Inheritance
public
– accessible to all classes
private
– accessible only within that class. Hidden from all sub
classes.
protected
– accessible by classes within the same package and all
descendant classes
Instance variables are typically private
protected methods are used to allow descendant
classes to modify instance variables in ways other
classes can't
CS 314 Inheritance 30
Why private Vars and not protected?
In general it is good practice to make
instance variables private
– hide them from your descendants
– if you think descendants will need to access
them or modify them provide protected methods
to do this
Why?
Consider the following example
CS 314 Inheritance 31
Required update
public class GamePiece {
private Board myBoard;
private Position myPos;
CS 314 Inheritance 32
Topic 5
Polymorphism
1
Polymorphism
Another feature of OOP
“having many forms”
object variables in Java are polymorphic
object variables can refer to objects of their
declared type AND any objects that are
descendants of the declared type
Property p = new Property();
p = new Railroad(); // legal!
p = new Utility(); //legal!
p = new Street();
Object obj1; // = what?
CS314 Polymorphism 2
Data Type
object variables have:
– a declared type. Also called the static type.
– a dynamic type. What is the actual type of the
pointee at run time or when a particular
statement is executed.
Method calls are syntactically legal if the
method is in the declared type or any
ancestor of the declared type
The actual method that is executed at
runtime is based on the dynamic type
– dynamic dispatch
CS314 Polymorphism 3
Clicker Question 1
Consider the following class declarations:
public class BoardSpace
public class Property extends BoardSpace
public class Street extends Property
public class Railroad extends Property
Which of the following statements would cause a syntax
error? (Assume all classes have a zero argument
constructor.)
A. Object obj = new Railroad();
B. Street s = new BoardSpace();
C. BoardSpace b = new Street();
D. Railroad r = new Street();
E. More than one of these
CS314 Polymorphism 4
Method LookUp
To determine if a method is legal the compiler looks in the
class of the declared type
– if it finds it great, if not go to the super class and look there
– continue until the method is found, or the Object class is reached
and the method was never found. (Compile error)
To determine which method is actually executed the run
time system (abstractly):
– starts with the actual run time class of the object that is calling the
method
– search the class for that method
– if found, execute it, otherwise go to the super class and keep looking
– repeat until a version is found
Is it possible the runtime system won’t find a method?
CS314 Polymorphism 5
Clicker Question 2
What is output by the public class Animal {
public String bt(){ return "!"; }
code to the right when }
run?
A. !!live public class Mammal extends Animal {
public String bt(){ return "live"; }
B. !eggegg }
CS314 Polymorphism 6
Clicker Question 3
public class Animal {
What is output by public void show() {
the code to the System.out.print(this.speak());
}
right when run? public String speak() { return "Em"; }
Think carefully }
about the dynamic
public class Dog extends Animal {
type. public String speak() { return "Woof"; }
A. MeowWoof }
D. EmEm }
CS314 Polymorphism 9
A Generic List Class
CS314 Polymorphism 10
Back to IntList
We may find IntList useful, but what if we
want a List of Strings? Rectangles?
Lists?
– What if I am not sure?
Are the List algorithms different if I am
storing Strings instead of ints?
How can we make a generic List class?
CS314 Polymorphism 11
Generic List Class
required changes
How does toString have to change?
– why?!?!
– A good example of why keyword this is
necessary from toString
What can a List hold now?
How many List classes do I need?
CS314 Polymorphism 12
Clicker 4
After altering the data type of the elements to
Object in our list class, how many lines of
code in the toString method, originally from
the IntList class, need to be changed?
A. 0
B. 1
C. 2
D. 3
E. >= 4
CS314 Polymorphism 13
Writing an equals Method
How to check if two objects are equal?
if(objA == objA)
// does this work?
Why not this
public boolean equals(List other)
Because
public void foo(List a, Object b)
if( a.equals(b) )
System.out.println( same )
– what if b is really a List?
CS314 Polymorphism 14
equals method
read the javadoc carefully!
Must handle null
Parameter must be Object
– otherwise overloading instead of overriding
– causes
must handle cases when parameter is not
same data type as calling object
– instanceof or getClass()
don't rely on toString and then String's
equals (efficiency)
CS314 Polymorphism 15
the createASet example
public Object[] createASet(Object[] items)
{ /*
pre: items != null, no elements
of items = null
post: return an array of Objects
that represents a set of the elements
in items. (all duplicates removed)
*/
CS314 Polymorphism 16
createASet examples
String[] sList = {"Texas", "texas", "Texas",
"Texas", "UT", "texas"};
Object[] sSet = createASet(sList);
for(int i = 0; i < sSet.length; i++)
System.out.println( sSet[i] );
CS314 Polymorphism 17
Topic 6
Generic Type Parameters
CS314 Generics 2
Using Object
In Java, all classes inherit from exactly one
other class except Object which is at the top
of the class hierarchy
– therefore all classes are descendants of Object
object variables can refer to objects of their
declared type and any descendants
– polymorphism
Thus, if the internal storage container is of
type Object it can hold anything
– primitives handled by wrapping them in objects.
int – Integer, char - Character
CS314 Generics 3
Difficulties with Object
Creating generic data structures using the
Object data type and polymorphism is
relatively straight forward
Using these generic data structrues leads to
some difficulties
– Casting
– Type checking
Code examples on the following slides
CS314 Generics 4
Clicker 1
What is output by the following code?
GenericList list = new GenericList(); // 1
Street s = new Street("Boardwalk", 400,
Color.BLUE);
list.add(s); // 2
System.out.print(list.get(0).getPrice());// 3
A. 400
B. No output due to syntax error at line // 1
C. No output due to syntax error at line // 2
D. No output due to syntax error at line // 3
E. No output due to runtime error.
CS314 Generics 5
Code Example - Casting
Assume a list class
GenericList li = new GenericList();
li.add("Hi");
System.out.println(li.get(0).charAt(0));
// previous line has syntax error
// return type of get is Object
// Object does not have a charAt method
// compiler relies on declared type
System.out.println(
((String) li.get(0)).charAt(0) );
// must cast to a String
CS314 Generics 6
Code Example – type checking
//pre: all elements of li are Monopoly Properties
public void printPrices(GenericList li) {
for (int i = 0; i < li.size(); i++) {
Property temp = (Property) li.get(i);
System.out.println(temp.getPrice());
}
}
// what happens if pre condition not met?
CS314 Generics 7
"Fixing" the Method
//pre: all elements of li are Monopoly Properties
CS314 Generics 8
Clicker 2 - Too Generic?
Does this code compile?
GenericList list = new GenericList();
list.add("Olivia");
list.add(Integer.valueOf(12));
list.add(12); // autobox aka autowrap
list.add(new Rectangle(1, 2, 3, 4));
list.add(new GenericList());
A. No
B. Yes
CS314 Generics 9
Is this a bug or a feature?
CS314 Generics 10
Generic Types
Java has syntax for parameterized data types
Referred to as Generic Types in most of the
literature
A traditional parameter has a data type and can
store various values just like a variable
public void foo(int x)
Generic Types are like parameters, but the data
type for the parameter is data type
– like a variable that stores a data type
– this is an abstraction. Actually, all data type info is
erased at compile time and replaced with casts and,
typically, variables of type Object
CS314 Generics 11
Making our Array List Generic
Data type variables declared in class header
public class GenericList<E> {
The <E> is the declaration of a data type
parameter for the class
– any legal identifier: Foo, AnyType, Element,
DataTypeThisListStores
– Java style guide recommends terse identifiers
The value E stores will be filled in whenever
a programmer creates a new GenericList
GenericList<String> li =
new GenericList<>();
CS314 Generics 12
Modifications to GenericList
instance variable
private E[] myCon;
Parameters on
– add, insert, remove, insertAll
Return type on
– get
Changes to creation of internal storage
container
myCon = (E[]) new Object[DEFAULT_SIZE];
Constructor header does not change
CS314 Generics 13
Modifications to GenericList
Careful with the equals method
Recall type information is actually erased at
compile time.
– At runtime not sure what data type of elements
are. (Unless we get into reflection.)
use of wildcard
rely on the elements equals methods
CS314 Generics 14
Using Generic Types
Back to Java's ArrayList
ArrayList list1 = new ArrayList();
– still allowed, a "raw" ArrayList
– works just like our first pass at GenericList
– casting, lack of type safety
CS314 Generics 15
Using Generic Types
ArrayList<String> list2 =
new ArrayList<String>();
– for list2 E stores String
list2.add( "Isabelle" );
System.out.println(
list2.get(0).charAt(2) ); //ok
list2.add( new Rectangle() );
// syntax error
CS314 Generics 16
Parameters and Generic Types
Old version
//pre: all elements of li are Strings
public void printFirstChar(ArrayList li){
New version
//pre: none
public void printFirstChar(ArrayList<String> li){
Elsewhere
ArrayList<String> list3 = new ArrayList<String>();
printFirstChar( list3 ); // ok
ArrayList<Integer> list4 = new ArrayList<Integer>();
printFirstChar( list4 ); // syntax error
CS314 Generics 17
Generic Types and Subclasses
ArrayList<Shape> list5 =
new ArrayList<Shape>();
list5.add(new Rectangle());
list5.add(new Square());
list5.add(new Circle());
// all okay
list5 can store Shape objects and any
descendants of Shape
CS314 Generics 18
Topic 7
Interfaces
I once attended a Java user group meeting where James Gosling (one
of Java's creators) was the featured speaker. During the memorable
Q&A session, someone asked him: "If you could do Java over again,
what would you change?" "I'd leave out classes," he replied. After
the laughter died down, he explained that the real problem wasn't
classes per se, but rather implementation inheritance (the extends
relationship). Interface inheritance (the implements relationship)
is preferable.
- Allen Holub
Clicker 1
How many sorts do you want to have to write?
public static void selSort(double[] data) {
for (int i = 0; i < data.length; i++) {
int small = i;
for(int j = i + 1; j < data.length; j++) {
if (data[j] < data[small])
small = j;
}
double temp = data[i];
A. 0
data[i] = data[small];
data[small] = temp; B. 1
} C. 2
} D. 3
CS314 Interfaces E. >= 4
Why interfaces?
Interfaces allow the creation of abstract types
– "A set of data values and associated operations that are
precisely specified independent of any particular
implementation. "
– multiple implementations allowed
Interfaces allow a data type to be specified without
worrying about the implementation
– do design first
– What will this data type do?
– Don’t worry about implementation until design is done.
– separation of concerns.
– allow us to create generic algorithms
CS314 Interfaces 3
Interfaces
public interface List<E> {
No constructors
No instance variables
abstract instance methods
public void add(E val);
default instance methods
static methods
class constants (prefer enums)
public static final int DEFAULT_CAP = 10;
CS314 Interfaces 6
Comparable Interface
package java.lang;
CS314 Interfaces 9
Example compareTo
Suppose we have a class to
model playing cards
– Ace of Spades, King of Hearts,
Two of Clubs
each card has a suit and a
value, represented by ints
this version of compareTo will
compare values first and then
break ties with suits
CS314 Interfaces 10
compareTo in a Card class
public class Card implements Comparable<Card> {
CS314 Interfaces 11
Interfaces and Polymorphism
Interfaces may be used as the data type
for object variables
Can’t simply create objects of that type
Can refer to any objects that implement the
interface or descendants
Assume Card implements Comparable
Card c = new Card();
Comparable comp1 = new Card();
Comparable comp2 = c;
CS314 Interfaces 12
Clicker Question 3
Which of the following lines of code causes a
syntax error?
Comparable c1; // A
c1 = "Ann"; // B
Comparable c2 = "Kelly"; // C
int x = c2.compareTo(c1); // D
// E No syntax errors.
CS314 Interfaces 13
Why Make More Work?
Why bother implementing an interface such
as Comparable
– objects can use method that expect an interface type
Example if I implement Comparable:
Arrays.sort(Object[] a)
public static void sort(Object[] a)
All elements in the array must implement the
Comparable interface. Furthermore, all elements in
the array must be mutually comparable
objects of my type can be stored in data
structures that accept Comparables
CS314 Interfaces 14
A List Interface
What if we wanted to specify the operations
for a List, but no implementation?
Allow for multiple, different implementations.
Provides a way of creating abstractions.
– a central idea of computer science and
programming.
– specify "what" without specifying "how"
– "Abstraction is a mechanism and practice to
reduce and factor out details so that one can
focus on a few concepts at a time. "
CS314 Interfaces 15
List Interface
public interface List <E> {
public void add(E val);
public int size();
public E get(int location);
public void insert(int location, E val);
public E remove(int location);
}
CS314 Interfaces 16
One Sort
public static void sort(Comparable[] data) {
final int LIMIT = data.length – 1;
for(int i = 0; i < LIMIT; i++) {
int small = i;
for(int j = i + 1; j < data.length; j++) {
int d = data[j].compareTo(data[small]);
if (d < 0)
small = j;
}
Comparable temp = data[i];
data[i] = data[small];
data[small] = temp;
} // end of i loop
}
CS314 Interfaces 17
Topic 8
Iterators
"First things first, but not necessarily
in that order "
-Dr. Who
1
Iterators
ArrayList is part of the Java Collections
Framework
Collection is an interface that specifies the
basic operations every collection (data
structure) shall have
Some Collections don’t have a definite order
– Sets, Maps, Graphs
How to access all the items in a Collection
with no specified order?
CS314 2
Iterators
Iterator Interface
An iterator object is a "one shot" object
– it is designed to go through all the
elements of a Collection once
– if you want to go through the
elements of a Collection again you
have to get another iterator object
Iterators are obtained by calling
a method from the Collection
CS314 3
Iterators
Iterator Iterface Methods
The Iterator interface 3 methods we will use:
boolean hasNext()
//returns true if this iteration has more elements
E next()
//returns the next element in this iteration
//pre: hastNext()
void remove()
/*Removes from the underlying collection the last element
returned by the iterator.
pre: This method can be called only once per call to next.
After calling, must call next again before calling remove
again.
*/
CS314 4
Iterators
Clicker 1
Which of the following produces a syntax error?
ArrayList<String> list = new ArrayList<>();
Iterator<String> it1 = new Iterator(); // I
Iterator<String> it2 = new Iterator(list); // II
Iterator<String> it3 = list.iterator(); // III
A. I
B. II
C. III
D. I and II
E. II and III
CS314 5
Iterators
Iterator
Imagine a fence made up of fence posts and
rail sections
rails
fenceposts
CS314 6
Iterators
Fence Analogy
The iterator lives on the fence posts
The data in the collection are the rails
Iterator created at the far left post
As long as a rail exists to the right of the
Iterator, hasNext() is true
iterator object
CS314 7
Iterators
Fence Analogy
ArrayList<String> names = new ArrayList<>();
names.add("Jan");
names.add("Levi");
names.add("Tom");
names.add("Jose");
Iterator<String> it = names.iterator();
int i = 0;
CS314 8
Iterators
Fence Analogy
while(it.hasNext()) {
i++;
System.out.println(it.next());
}
// when i == 1, prints out Jan
first call to next moves iterator to
next post and returns "Jan"
"Jan" "Levi" "Tom" "Jose"
CS314 9
Iterators
Fence Analogy
while(it.hasNext()) {
i++;
System.out.println(it.next());
}
// when i == 2, prints out Levi
CS314 10
Iterators
Fence Analogy
while(it.hasNext()) {
i++;
System.out.println(it.next());
}
// when i == 3, prints out Tom
CS314 11
Iterators
Fence Analogy
while(it.hasNext()) {
i++;
System.out.println(it.next());
}
// when i == 4, prints out Jose
CS314 12
Iterators
Fence Analogy
while(it.hasNext()) {
i++;
System.out.println(it.next());
}
// call to hasNext returns false
// while loop stops
CS314 13
Iterators
Typical Iterator Pattern
public void printAll(Collection<String> col) {
Iterator<String> it = col.iterator();
while (it.hasNext()) {
String temp = it.next();
System.out.println(temp);
}
}
OR……
for (String temp : col) {
System.out.println(temp);
}
CS314 14
Iterators
Clicker Question 2
What is output by the following code?
ArrayList<Integer> list = new ArrayList<>();
list.add(3);
list.add(3);
list.add(5);
Iterator<Integer> it = list.iterator();
System.out.print(it.next() + " ");
System.out.print(it.next() + " ");
System.out.print(it.next());
A. 3 B. 3 5 C. 3 3 5
D. 3 3 E. 3 3 then a runtime error
15
remove method
An Iterator can be used to remove things from
the Collection
Can only be called once per call to next()
public void removeWordsOfLength(int len) {
Iterator<String> it = myList.iterator
while(it.hasNext()) {
String temp = it.next();
if (temp.length() == len) {
it.remove();
}
}
}
// original list = ["dog", "cat", "hat", "sat"]
// resulting list after removeWordsOfLength(3) ?
CS314 16
Iterators
Clicker 3
public void printTarget(Collection<String>
names, int len) {
Iterator<String> it = names.iterator();
while(it.hasNext())
if(it.next().length() == len)
System.out.println(it.next());
}
Given names = ["Jan", "Ivan", "Tom", "George"] and len = 3 what is output
by the printTarget method?
A. Jan Ivan Tom George
B. Jan Tom
C. Ivan George
D. No output due to syntax error
E. No output due to runtime error 17
The Iterable Interface
A related interface is Iterable
The method of interest to us in the interface:
public Iterator<T> iterator()
Why?
Anything that implements the Iterable
interface can be used in the for each loop.
ArrayList<Integer> list;
//code to create and fill list
int total = 0;
for (int x : list) {
total += x;
}
CS314 18
Iterators
Iterable
If you simply want to go through all the
elements of a Collection (or Iterable thing)
use the for each loop
– hides creation of the Iterator
public void printAllOfLength(ArrayList<String> names,
int len){
//pre: names != null, names only contains Strings
//post: print out all elements of names equal in
// length to len
for (String s : names)
if (s.length() == len)
System.out.println(s);
}
CS314 19
Iterators
Implementing an Iterator
Implement an Iterator for our GenericList
class
– Nested Classes
– Inner Classes
– Example of encapsulation
– checking precondition on remove
– does our GenricList need an Iterator?
CS314 20
Iterators
Madilyn L. 2019
Comodification
If a Collection (ArrayList) is changed
while an iteration via an iterator is in progress
an Exception will be thrown the next time the
next() or remove() methods are called
via the iterator
ArrayList<String> names = new ArrayList<>();
names.add("Jan");
Iterator<String> it = names.iterator();
names.add("Andy");
it.next(); // exception occurs here
CS314 21
Iterators
Topic 9
Using Maps
1
Data Structures
More than arrays and lists
Write a program to determine the frequency
of all the "words" in a file.
CS 314 Maps 2
Performance using ArrayList
Title Size Total Distinct Time
(kb) Words Words (sec)
small sample 0.6 89 25 0.001
2BR02B 34 5,638 1,975 0.051
Alice in 120 29,460 6,017 0.741
Wonderland
Adventures of 581 107,533 15,213 4.144
Sherlock Holmes
2008 CIA Factbook 10,030 1,330,100 74,042 173.000
CS 314 Maps 3
Order?
Express change of value as factor of previous file
Title Size Total Distinct Time
Words Words
small sample 0.6 89 25 0.001
2BR02B 57x 63x 79x 51x
Alice in 3.5x 5.2x 3.0x 14.5x
Wonderland
Adventures of 4.8x 3.7x 2.5x 6.0x
Sherlock Holmes
2008 CIA Factbook 17x 12.3x 5x 42x
CS 314 Maps 4
Clicker 1
Given 10 seconds for the 2008 CIA Factbook
with 1,330,100 total words and 74,042
distinct words, how long for 1,000x total
words and 100x distinct words?
A. an hour
B. a day
C. a week
D. a month
E. half a year
CS 314 Maps 5
Why So Slow??
Write a contains method for an array based list
CS 314 Maps 6
A Faster Way - Maps
Also known as:
– table, search table, dictionary, associative array, or
associative container
A data structure optimized for a very specific kind
of search / access
In a map we access by asking "give me the value
associated with this key."
CS 314 Maps 7
Keys and Values
Dictionary Analogy:
– The key in a dictionary is a word:
foo
– The value in a dictionary is the definition:
First on the standard list of metasyntactic
variables used in syntax examples
A key and its associated value form a pair
that is stored in a map
To retrieve a value the key for that value
must be supplied
– A List can be viewed as a Map with integer keys
CS 314 Maps 8
More on Keys and Values
Keys must be unique, meaning a given key
can only represent one value
– but one value may be represented by multiple
keys
– like synonyms in the dictionary.
Example:
factor: n.See coefficient of X
– factor is a key associated with the same value
(definition) as the key coefficient of X
CS 314 Maps 9
Clicker 2
Is it required that the keys and values of a
map be the same data type?
A. No
B. Yes
C. It Depends
CS 314 Maps 10
Map <String, List<String>>
Movie Characters
CS 314 Maps 12
The Map Interface Continued
V get(Object key)
– Returns the value to which this map maps the
specified key. Returns null if key not present.
boolean isEmpty()
– Returns true if this map contains no key-value
mappings.
V put(K key, V value)
– Associates the specified value with the specified
key in this map
CS 314 Maps 13
The Map Interface Continued
V remove(Object key)
– Removes the mapping for this key from this map
if it is present
int size()
– Returns the number of key-value mappings in
this map.
Collection<V> values()
– Returns a collection view of the values contained
in this map.
CS 314 Maps 14
Results with HashMap
Title Size Total Distinct Time Time
(kb) Words Words List Map
small sample 0.6 89 25 0.001 0.0008
2BR02B 34 5,638 1,975 0.051 0.0140
Alice in 120 29,460 6,017 0.741 0.0720
Wonderland
Adventures of 581 107,533 15,213 4.144 0.2500
Sherlock Holmes
2008 CIA Factbook 10,030 1,330,100 74,042 173.000 4.0000
CS 314 Maps 15
Order?
Title Size Total Distinct Time Time
Words Words List Map
small sample 0.6 89 25 0.001 0.0008
2BR02B 57x 63x 79x 51x 18x
Alice in 3.5x 5.2x 3.0x 14.5x 5x
Wonderland
Adventures of 4.8x 3.7x 2.5x 5.6x 3.5x
Sherlock Holmes
2008 CIA 17x 12.3x 5x 42x 16x
Factbook
O(Total Words)?
CS 314 Maps 16
Topic 10
Abstract Classes
“I prefer Agassiz in the
abstract, rather than in
the concrete.”
- Statue of Biologist
Louis Agassiz that fell from
a ledge on the Stanford
Quad during the 1906
San Francisco earthquake.
1
Back to the Monopoly Property Example
There are properties on a
monopoly board
Railroads, Utilities, and Streets are
kinds of properties
Property
}
Methods that are declared abstract have no body
an undefined behavior.
All non-default methods in a Java interface are
abstract.
CS314 Abstract Classes 10
Problems with Abstract Methods
Given getRent() is now an abstract method
what is wrong with the following code?
}
// Other methods not shown
-Joel Spolsky
1
Sam G. - Fall 2023
CS314 2
Linked Lists
Clicker 1
What is output by the following code?
ArrayList<Integer> a1 = new ArrayList<>();
ArrayList<Integer> a2 = new ArrayList<>();
a1.add(12);
a2.add(12);
System.out.println(a1 == a2);
A. false
B. true
C. No output due to syntax error
D. No output due to runtime error
E. Varies from one run of the program to the next
CS314 3
Linked Lists
Dynamic Data Structures
Dynamic data structures
– They grow and shrink one element at a time,
normally without some of the inefficiencies of
arrays
– as opposed to a static container such as an array
Big O of Array Manipulations
– Access the kth element
– Add or delete an element in the middle of the
array while maintaining relative order
– adding element at the end of array? space
avail? no space avail?
– add element at beginning of an array
CS314 4
Linked Lists
Object References
Recall that an object reference is a variable
that stores the address of an object
CS314 5
Linked Lists
References as Links
Object references can be used to create
links between objects
CS314 6
Linked Lists
References as Links
References can be used to create a variety
of linked structures, such as a linked list:
studentList
CS314 7
Linked Lists
Linked Lists
A linear collection of self-referential objects,
typically called nodes, connected by other links
– linear: for every node in the list, there is one and only one node
that precedes it (except for possibly the first node, which may
have no predecessor,) and there is one and only one node that
succeeds it, (except for possibly the last node, which may have
no successor)
– Usually a list will have a beginning and an end; the first element
in the list is accessed by a reference to that class, and the last
node in the list will have a reference that is set to null
CS314 8
Linked Lists
Advantages of linked lists
Linked lists are dynamic, they can grow or shrink
as necessary
CS314 9
Linked Lists
Nodes and Lists
A different way of implementing a list
Each element of a Linked List is a separate
Node object.
Each Node tracks a single piece of data plus
a reference (pointer) to the next
Create a new Node very time we add
something to the List
Remove nodes when item removed from list
and allow garbage collector to reclaim that
memory
CS314 10
Linked Lists
A Node Class
public class Node<E> {
private E myData;
private Node<E> myNext;
public Node()
{ myData = null; myNext = null; }
public E getData()
{ return myData; }
CS314 11
Linked Lists
One Implementation of a Linked List
The Nodes show on the previous slide are
singly linked
– a node refers only to the next node in the
structure
– it is also possible to have doubly linked nodes.
– The node has a reference to the next node in the
structure and the previous node in the structure
as well
How is the end of the list indicated
– myNext = null for last node
– a separate dummy node class / object
CS314 12
Linked Lists
A Linked List Implementation
public class LinkedList<E> implements IList<E>
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedList(){
head = null;
tail = null;
size = 0;
}
}
LinkedList<String> list = new LinkedList<String>();
LinkedList
myHead null iMySize 0
myTail null
CS314 13
Linked Lists
Writing Methods
When trying to code methods for Linked
Lists draw pictures!
– If you don't draw pictures of what you are trying
to do it is very easy to make mistakes!
CS314 14
Linked Lists
add method
add to the end of list
special case if empty
steps on following slides
public void add(E obj)
CS314 15
Linked Lists
Add Element - List Empty (Before)
head tail size
null null 0
Object
item
CS314 16
Linked Lists
Add Element - List Empty (After)
head tail size
1
Node
String
myData myNext
null
CS314 17
Linked Lists
Add Element - List Not Empty (Before)
head tail size
1
Node
myData myNext
null
String String
item
CS314 18
Linked Lists
Add Element - List Not Empty (After)
head tail size
2
Node Node
myData myNext myData myNext
null
String String
CS314 19
Linked Lists
Code for default add
public void add(E obj)
CS314 20
Linked Lists
Clicker 2
What is the worst case Big O for adding to
the end of an array based list and our
LinkedList314 class? The lists already
contain N items.
Array based Linked
A. O(1) O(1)
B. O(N) O(N)
C. O(logN) O(1)
D. O(1) O(N)
E. O(N) O(1)
21
Contains method
Implement a contains method for our Linked
List class
public boolean contains(E val) // val != null
CS314 22
Linked Lists
Code for addFront
add to front of list
public void addFront(E obj)
How does this compare to adding at the front
of an array based list?
CS314 23
Linked Lists
Clicker 3
What is the Big O for adding to the front of
an array based list and a linked list? The lists
already contain N items.
Array based Linked
A. O(1) O(1)
B. O(N) O(1)
C. O(logN) O(1)
D. O(1) O(N)
E. O(N) O(N)
CS314 24
Linked Lists
Code for Insert
public void insert(int pos, E obj)
Must be careful not to break the chain!
Where do we need to go?
Special cases?
CS314 25
Linked Lists
Clicker 4
What is the Big O for inserting an element
into the middle of an array based list and into
the middle of a linked list? Each list already
contains N items.
Array based Linked
A. O(1) O(1)
B. O(1) O(N)
C. O(N) O(1)
D. O(N) O(N)
E. O(N) O(logN)
CS314 26
Linked Lists
Clicker Question 5
What is the Big O for getting an element
based on position from an array based list
and from a linked list? Each list contains N
items. In other words E get(int pos)
Array based Linked
A. O(1) O(1)
B. O(1) O(N)
C. O(N) O(1)
D. O(logN) O(N)
E. O(N) O(N)
27
Linked Lists
Code for get
public E get(int pos)
The downside of Linked Lists
CS314 28
Linked Lists
Code for remove
public E remove(int pos)
CS314 29
Linked Lists
Clicker 6
What is the order to remove the last element
of a singly linked list with references to the
first and last nodes of the linked structure of
nodes?
The list contains N elements
A. O(1)
B. O(logN)
C. O(N^0.5)
D. O(N)
E. O(NlogN))
CS314 30
Linked Lists
Why Use Linked List
What operations with a Linked List faster
than the version from ArrayList?
CS314 31
Linked Lists
Clicker 7 - Getting All Elements in
Order From a Linked List
What is the Order (Big O) of the following code?
LinkedList314<Integer> list;
list = new LinkedList314<Integer>();
// code to fill list with N elements
int total = 0;
//Big O of following code?
for(int i = 0; i < list.size(); i++)
total += list.get(i);
A. O(N) B. O(2N) C. O(NlogN)
D. O(N2) E. O(N3)
CS314 32
Linked Lists
Iterators to the Rescue
CS314 33
Linked Lists
Other Possible Features of
Linked Lists
Doubly Linked
Circular
Dummy Nodes for first and last node in list
public class DLNode<E> {
private E myData;
private DLNode<E> myNext;
private DLNode<E> myPrevious;
CS314 34
Linked Lists
Dummy Nodes
Use of Dummy Nodes for a Doubly Linked
List removes most special cases
Also could make the Double Linked List
circular
CS314 35
Linked Lists
Doubly Linked List add
CS314 36
Linked Lists
Insert for Doubly Linked List
public void insert(int pos, E obj)
CS314 37
Linked Lists
Topic 12
Introduction to Recursion
"To a man with a hammer,
everything looks like a nail"
-Mark Twain
Underneath the Hood.
CS314 Recursion 2
The Program Stack
When you invoke a method in your code
what happens when that method is done?
public class Mice {
public static void main(String[] args) {
int x = 37;
int y = 12;
method1(x, y);
int z = 73;
int m1 = method1(z, x);
method2(x, x);
}
CS314 Recursion 10
Using Recursion
A Problem
Write a method that determines how much
space is take up by the files in a directory
A directory can contain files and
directories
How many directories does our code have
to examine?
How would you add up the space taken
up by the files in a single directory
– Hint: don't worry about any sub directories at
first
CS314 Recursion 12
Clicker 2
How many levels of directories have to be
visited?
A. 0
B. 1
C. 8
D. Infinite
E. Unknown
CS314 Recursion 13
Sample Directory Structure
scottm
cs314 AP
m1.txt m2.txt
A.pdf
AB.pdf
hw
CS314 Recursion 14
Java File Class
File(String pathname) Creates a new
File instance by converting the given
pathname.
boolean isDirectory() Tests whether
the file denoted by this abstract pathname is
a directory.
File[] listFiles() Returns an array
of abstract pathnames denoting the files in
the directory denoted by this abstract
pathname.
CS314 Recursion 15
Code for getDirectorySpace()
// pre: dir is a directory and dir != null
public static long spaceUsed(File dir) {
if( dir == null || !dir.isDirectory())
throw new IllegalArgumentException();
long spaceUsed = 0;
File[] subFilesAndDirs = dir.listFiles();
if(subFilesAndDirs != null)
for(File sub : subFilesAndDirs)
if(sub != null)
if(sub.isFile()) // sub is a plain old file
spaceUsed += sub.length();
else if (sub.isDirectory())
// else sub is a directory
spaceUsed += spaceUsed(sub);
return spaceUsed;
} 16
Clicker 3
Is it possible to write a non recursive method
to determine space taken up by files in a
directory, including its subdirectories, and
their subdirectories, and their subdirectories,
and so forth?
A. No
B. Yes
C. It Depends
CS314 Recursion 17
Iterative getDirectorySpace()
public long getDirectorySpace(File d) {
ArrayList<File> dirs = new ArrayList<>();
dirs.add(d);
long total = 0;
while (dirs.size() > 0) {
File temp = dirs.remove(dirs.size() – 1);
File[] filesAndSubs = temp.listFiles();
if (filesAndSubs != null) {
for (File f : filesAndSubs) {
if (f != null) {
if (f.isFile())
total += f.length();
else if (f.isDirectory())
dirs.add(f);
}
}
}
return total;
}
CS314 Recursion 18
Wisdom for Writing Recursive
Methods
The 3 plus 1 rules of Recursion
1. Know when to stop
2. Decide how to take one step
3. Break the journey down into that step and a
smaller journey
4. Have faith
CS314 Recursion 20
Writing Recursive Methods
Rules of Recursion
1. Base Case: Always have at least one case that
can be solved without using recursion
2. Make Progress: Any recursive call must
progress toward a base case.
3. "You gotta believe." Always assume that the
recursive call works. (Of course you will have to
design it and test it to see if it works or prove
that it always works.)
A recursive solution solves a small part of
the problem and leaves the rest of the
problem in the same form as the original
CS314 Recursion 21
N!
the classic first recursion problem / example
N!
5! = 5 * 4 * 3 * 2 * 1 = 120
int res = 1;
for(int i = 2; i <= n; i++)
res *= i;
CS314 Recursion 22
Factorial Recursively
Mathematical Definition of Factorial
for N >= 0, N! is:
0! = 1
N! = N * (N - 1)! (for N > 0)
The definition is recursive.
// pre n >= 0
public int fact(int n) {
if(n == 0)
return 1;
else
return n * fact(n-1);
} // return (n == 0) ? 1 : n * fact(n - 1);
CS314 Recursion 23
Tracing Fact With the
Program Stack
System.out.println( fact(4) );
n 4 in method fact
partial result = n * fact(n-1)
top System.out.println( fact(4) );
CS314 Recursion 25
Calling fact with 3
n 3 in method fact
partial result = n * fact(n-1)
n 2 in method fact
partial result = n * fact(n-1)
n 4 in method fact
partial result = n * fact(n-1)
System.out.println( fact(4) );
CS314 Recursion 27
Calling fact with 1
n 1 in method fact
partial result = n * fact(n-1)
n 3 in method fact
partial result = n * fact(n-1)
n 4 in method fact
partial result = n * fact(n-1)
System.out.println( fact(4) );
CS314 Recursion 28
Calling fact with 0 and returning 1
n 0 in method fact
returning 1 to whatever method called me
n 3 in method fact
partial result = n * fact(n-1)
n 4 in method fact
partial result = n * fact(n-1)
CS314 Recursion 29
System.out.println( fact(4) );
Returning 1 from fact(1)
n 1 in method fact
partial result = n * 1,
return 1 to whatever method called me
n 3 in method fact
partial result = n * fact(n-1)
n 4 in method fact
partial result = n * fact(n-1)
System.out.println( fact(4) );
CS314 Recursion 30
Returning 2 from fact(2)
n 2 in method fact
partial result = 2 * 1,
return 2 to whatever method called me
n 4 in method fact
partial result = n * fact(n-1)
System.out.println( fact(4) );
CS314 Recursion 31
Returning 6 from fact(3)
n 3 in method fact
partial result = 3 * 2,
return 6 to whatever method called me
CS314 Recursion 32
Returning 24 from fact(4)
n 4 in method fact
partial result = 4 * 6,
return 24 to whatever method called me
top System.out.println( fact(4) );
CS314 Recursion 33
Calling System.out.println
System.out.println( 24 );
top ??
CS314 Recursion 34
Evaluating Recursive Methods
Evaluating Recursive Methods
you must be able to evaluate recursive
methods
public static int mystery (int n){
if(n == 0)
return 2;
else
return 3 * mystery(n-1);
}
// what is returned by mystery(3)
CS314 Recursion 36
Evaluating Recursive Methods
Draw the program stack!
m(3) = 3 * m(2) -> 3 * 18 = 54
m(2) = 3 * m(1) -> 3 * 6 = 18
m(1) = 3 * m(0) -> 3 * 2 = 6
m(0) = 2
-> 54
CS314 Recursion 37
Clicker 4
What is returned by fact(-3) ?
A. 0
B. 1
C. Infinite loop
D. Syntax error
E. Runtime error
public static int fact(int n) {
if (n == 0) {
return 1;
} else {
return n * fact(n - 1);
}
38
}
Evaluating Recursive Methods
What about multiple recursive calls?
public static int bar(int n){
if (n <= 0)
return 2;
else
return 3 + bar(n-1) + bar(n-2);
}
Clicker 5 - What does bar(4) return?
A. 2 B. 3 C. 12 D. 22 E. 37
CS314 Recursion 39
Evaluating Recursive Methods
What is returned by bar(4)?
b(4) = 3 + b(3) + b(2)
b(3) = 3 + b(2) + b(1)
b(2) = 3 + b(1) + b(0)
b(1) = 3 + b(0) + b(-1)
b(0) = 2
b(-1) = 2
CS314 Recursion 40
Evaluating Recursive Methods
What is returned by bar(4)?
b(4) = 3 + b(3) + b(2)
b(3) = 3 + b(2) + b(1)
b(2) = 3 + b(1) + b(0) //substitute in results
b(1) = 3 + 2 + 2 = 7
b(0) = 2
b(-1) = 2
CS314 Recursion 41
Evaluating Recursive Methods
What is returned by bar(4)?
b(4) = 3 + b(3) + b(2)
b(3) = 3 + b(2) + b(1)
b(2) = 3 + 7 + 2 =12
b(1) = 7
b(0) = 2
b(-1) = 2
CS314 Recursion 42
Evaluating Recursive Methods
What is returned by bar(4)?
b(4) = 3 + b(3) + b(2)
b(3) = 3 + 12 + 7 = 22
b(2) = 12
b(1) = 7
b(0) = 2
b(-1) = 2
CS314 Recursion 43
Evaluating Recursive Methods
What is returned by bar(4)?
b(4) = 3 + 22 + 12 = 37
b(3) = 22
b(2) = 12
b(1) = 7
b(0) = 2
b(-1) = 2
CS314 Recursion 44
Recursion Practice
Write a method raiseToPower(int base,
int power)
//pre: power >= 0
CS314 Recursion 45
Finding the Maximum in an Array
public int max(int[] data) {
Helper method or create smaller arrays each
time
CS314 Recursion 46
Clicker 6
When writing recursive methods what should
be done first?
A. Determine recursive case
B. Determine recursive step
C. Make a recursive call
D. Determine base case(s)
E. Determine the Big O
CS314 Recursion 47
Your Meta Cognitive State
Remember we are learning to use a tool.
It is not a good tool for all problems.
– In fact we will implement several algorithms and
methods where an iterative (looping without
recursion) solution would work just fine
After learning the mechanics and basics of
recursion the real skill is knowing what
problems or class of problems to apply it to
CS314 Recursion 48
Big O and Recursion
Determining the Big O of recursive methods
can be tricky.
A recurrence relation exits if the function is
defined recursively.
The T(N), actual running time, for N! is
recursive
T(N)fact = T(N-1)fact + O(1)
This turns out to be O(N)
– There are N steps involved
CS314 Recursion 49
Common Recurrence Relations
T(N) = T(N/2) + O(1) -> O(logN)
– binary search
T(N) = T(N-1) + O(1) -> O(N)
– sequential search, factorial
T(N) = T(N/2) + T(N/2) + O(1) -> O(N),
– tree traversal
T(N) = T(N-1) + O(N) -> O(N^2)
– selection sort
T(N) = T(N/2) + T(N/2) + O(N) -> O(NlogN)
– merge sort
T(N) = T(N-1) + T(N-1) + O(1) -> O(2^N)
– Fibonacci
CS314 Recursion 50
Topic 13
Recursive Backtracking
"In ancient times, before computers were invented,
alchemists studied the mystical properties of
numbers. Lacking computers, they had to rely on
dragons to do their work for them. The dragons
were clever beasts, but also lazy and bad-tempered.
The worst ones would sometimes burn their keeper
to a crisp with a single fiery belch. But most dragons
were merely uncooperative, as violence required too
much energy. This is the story of how Martin, an
alchemist’s apprentice, discovered recursion by
outsmarting a lazy dragon."
- David S. Touretzky, Common Lisp: A Gentle Introduction to
Symbolic Computation
Success!
Failure
Problem space consists of states (nodes) and actions
(paths that lead to new states). When in a node can
can only see paths to connected nodes
Current
Room
CS314 3
Recursive Backtracking
Escaping a Maze
Try door to the east
Doors
First Current
room Room
CS314 4
Recursive Backtracking
Escaping a Maze
Back we go
Doors
Current
Room
A dead end!
CS314 5
Recursive Backtracking
Escaping a Maze
What if we knew the exit was to the south?
Doors
Current
Room
CS314 6
Recursive Backtracking
Escaping a Maze
Start over. What if we knew the exit was to
the south?
Doors
Current
Room
Exit out there,
some where
to the south!
A dead end!
CS314 8
Recursive Backtracking
Escaping a Maze
What if we knew the exit was to the south?
Doors
CS314 9
Recursive Backtracking
Escaping a Maze
What if we knew the exit was to the south?
Doors
Current
Exit out there, Room
some where
to the south!
A dead end!
CS314 10
Recursive Backtracking
Escaping a Maze
Doors
A dead end!
Doors
Current
A dead end!
Room
Doors
A dead end!
CS314 15
Recursive Backtracking
Another Concrete Example
Sudoku
9 by 9 matrix with some
numbers filled in
all numbers must be between
1 and 9
Goal: Each row, each column,
and each mini matrix must
contain the numbers between
1 and 9 once each
– no duplicates in rows, columns,
or mini matrices
CS314 16
Recursive Backtracking
Solving Sudoku – Brute Force
A brute force algorithm is a
simple but generally
inefficient approach
Try all combinations until
you find one that works
This approach isn’t clever,
but computers are fast
Then try and improve on
the brute force results
CS314 17
Recursive Backtracking
Solving Sudoku
Brute force Sudoku Soluton
– if not open cells, solved 1
– scan cells from left to right,
top to bottom for first open
cell
– When an open cell is found
start cycling through digits 1
to 9.
– When a digit is placed check
that the set up is legal
– now solve the board
CS314 18
Recursive Backtracking
Clicker 1
After placing a number in a cell is the
remaining problem very similar to the original
problem?
A. No
B. Yes
CS314 19
Recursive Backtracking
Solving Sudoku – Later Steps
1 1 2 1 2 4
1 2 4 8 1 2 4 8 9
uh oh!
CS314 20
Recursive Backtracking
Sudoku – A Dead End
We have reached a dead end in our search
1 2 4 8 9
CS314 22
Recursive Backtracking
Characteristics of Brute Force
and Backtracking
Brute force algorithms are slow
The first pass attempts typically don't employ
a lot of logic
But, brute force algorithms are fairly easy to
implement as a first pass solution
– many backtracking algorithms are brute force
algorithms
CS314 23
Recursive Backtracking
Key Insights
After trying placing a digit in a cell we want to solve
the new sudoku board
– Isn't that a smaller (or simpler version) of the same
problem we started with?!?!?!?
After placing a number in a cell the we need to
remember the next number to try in case things
don't work out.
We need to know if things worked out (found a
solution) or they didn't, and if they didn't try the next
number
If we try all numbers and none of them work in our
cell we need to report back that things didn't work
CS314 24
Recursive Backtracking
Clicker 2
Grace 2019 Asked: When we reach the base
case in the solveSudoku method (9 x 9
board) and before we return true, how many
stack frames are on the program stack of the
solveSudoku method? Pick the closest
answer.
A. <= 9
B. 82
C. 819
D. 981
E. cannot determine 25
Recursive Backtracking
Problems such as Suduko can be solved
using recursive backtracking
recursive because later versions of the
problem are just slightly simpler versions of
the original
backtracking because we may have to try
different alternatives
CS314 26
Recursive Backtracking
Recursive Backtracking - Repeated
Pseudo code for recursive backtracking
algorithms – looking for a solution
CS314 27
Recursive Backtracking
Goals of Backtracking
Possible goals
– Find a path to success
– Find all paths to success
– Find the best path to success
Not all problems are exactly alike, and
finding one success node may not be the
end of the search
Start
Success!
Success!
CS314 28
Recursive Backtracking
The 8 N Queens Problem
CS314 29
Recursive Backtracking
The 8 Queens Problem
A classic chess puzzle
– Place 8 queen pieces on a chess board so that
none of them can attack one another
CS314 30
Recursive Backtracking
The N Queens Problem
Place N Queens on an N by N chessboard so that
none of them can attack each other
Number of possible placements?
In 8 x 8
64 * 63 * 62 * 61 * 60 * 59 * 58 * 57
= 178,462, 987, 637, 760 / 8!
= 4,426,165,368
n choose k
– How many ways can you choose k things from a
set of n items?
– In this case there are 64 squares and we want to choose
8 of them to put queens on
CS314 31
Recursive Backtracking
Clicker 3
For a safe solution, how many queens can
be placed in a given column?
A. 0
B. 1
C. 2
D. 3
E. Any number
CS314 32
Recursive Backtracking
Reducing the Search Space
The previous calculation includes set ups like this
one Q
Q
CS314 34
Recursive Backtracking
A Solution to 8 Queens
If number of queens is fixed and I realize there can't be
more than one queen per column I can iterate through the
rows for each column
for(int r0 = 0; r0 < 8; r0++){
board[r0][0] = 'q';
for(int r1 = 0; r1 < 8; r1++){
board[r1][1] = 'q';
for(int r2 = 0; r2 < 8; r2++){
board[r2][2] = 'q';
// a little later
for(int r7 = 0; r7 < 8; r7++){
board[r7][7] = 'q';
if( queensAreSafe(board) )
printSolution(board);
board[r7][7] = ' '; //pick up queen
}
board[r6][6] = ' '; // pick up queen
CS314 35
Recursive Backtracking
N Queens
The problem with N queens is you don't
know how many for loops to write.
Do the problem recursively
Write recursive code with class and demo
– show backtracking with breakpoint and
debugging option
CS314 36
Recursive Backtracking
Recursive Backtracking
You must practice!!!
Learn to recognize problems that fit the
pattern
Is a kickoff method needed?
All solutions or a solution?
Reporting results and acting on results
CS314 37
Recursive Backtracking
Minesweeper
CS314 38
Recursive Backtracking
Minesweeper Reveal
Algorithm
Minesweeper
click a cell
– if bomb game over
– if cell that has 1 or more bombs on border
then reveal the number of bombs that border cell
– if a cell that has 0 bombs on border
then reveal that cell as a blank and click on the 8
surrounding cells
CS314 39
Recursive Backtracking
Another Backtracking Problem
A Simple Maze
Search maze until way
out is found. If no way
out possible report that.
CS314 40
Recursive Backtracking
The Local View
Which way do
I go to get
out?
North
West
East
CS314 42
Recursive Backtracking
Backtracking in Action
The crucial part of the
algorithm is the for loop
that takes us through the
alternatives from the current
square. Here we have moved
to the North.
CS314 44
Recursive Backtracking
So the next move we
can make is West.
CS314 45
Recursive Backtracking
This path reaches
a dead end.
Time to backtrack!
Remember the
program stack!
CS314 46
Recursive Backtracking
The recursive calls
end and return until
we find
ourselves back here.
CS314 47
Recursive Backtracking
And now we try
South
CS314 48
Recursive Backtracking
Path Eventually Found
CS314 49
Recursive Backtracking
More Backtracking Problems
CS314 50
Recursive Backtracking
Other Backtracking Problems
Knight's Tour
Regular Expressions
Knapsack problem / Exhaustive Search
– Filling a knapsack. Given a choice of items with
various weights and a limited carrying capacity
find the optimal load out. 50 lb. knapsack. items
are 1 40 lb, 1 32 lb. 2 22 lbs, 1 15 lb, 1 5 lb. A
greedy algorithm would choose the 40 lb item
first. Then the 5 lb. Load out = 45lb. Exhaustive
search 22 + 22 + 5 = 49.
CS314 51
Recursive Backtracking
The CD problem
We want to put songs on a Compact Disc.
650MB CD and a bunch of songs of various
sizes.
If there are no more songs to consider return result
else{
Consider the next song in the list.
Try not adding it to the CD so far and use recursion to evaluate best
without it.
Try adding it to the CD, and use recursion to evaluate best with it
Whichever is better is returned as absolute best from here
}
CS314 52
Recursive Backtracking
Another Backtracking Problem
Airlines give out frequent flier miles as a way to get
people to always fly on their airline.
Airlines also have partner airlines. Assume if you
have miles on one airline you can redeem those
miles on any of its partners.
Further assume if you can redeem miles on a
partner airline you can redeem miles on any of its
partners and so forth...
– Airlines don't usually allow this sort of thing.
Given a list of airlines and each airlines partners
determine if it is possible to redeem miles on a
given airline A on another airline B.
CS314 53
Recursive Backtracking
Airline List – Part 1
Delta
– partners: Air Canada, Aero Mexico, OceanAir
United
– partners: Aria, Lufthansa, OceanAir, Quantas, British Airways
Northwest
– partners: Air Alaska, BMI, Avolar, EVA Air
Canjet
– partners: Girjet
Air Canda
– partners: Areo Mexico, Delta, Air Alaska
Aero Mexico
– partners: Delta, Air Canda, British Airways
CS314 54
Recursive Backtracking
Airline List - Part 2
Ocean Air
– partners: Delta, United, Quantas, Avolar
AlohaAir
– partners: Quantas
Aria
– partners: United, Lufthansa
Lufthansa
– partners: United, Aria, EVA Air
Quantas
– partners: United, OceanAir, AlohaAir
BMI
– partners: Northwest, Avolar
Maxair
– partners: Southwest, Girjet
CS314 55
Recursive Backtracking
Airline List - Part 3
Girjet
– partners: Southwest, Canjet, Maxair
British Airways
– partners: United, Aero Mexico
Air Alaska
– partners: Northwest, Air Canada
Avolar
– partners: Northwest, Ocean Air, BMI
EVA Air
– partners: Northwest, Luftansa
Southwest
– partners: Girjet, Maxair
CS314 56
Recursive Backtracking
Problem Example
If I have miles on Northwest can I redeem them on Aria?
Partial graph:
Ocean Air
BMI Avolar
Northwest
Air Alaska
EVA Air
CS314 57
Recursive Backtracking
Topic 14
Searching and Simple Sorts
"There's nothing in your head the
sorting hat can't see. So try me
on and I will tell you where you
ought to be."
-The Sorting Hat, Harry Potter
and the Sorcerer's Stone
Sorting and Searching
Fundamental problems in computer science
and programming
Sorting done to make searching easier
Multiple different algorithms to solve the
same problem
– How do we know which algorithm is "better"?
Look at searching first
Examples use arrays of ints to illustrate
algorithms
data
Variables of Interest?
Stacks
Lists
CS314 2
Stacks
Stacks
Access is allowed only at one point of the structure,
normally termed the top of the stack
– access to the most recently added item only
Operations are limited:
– push (add item to stack)
– pop (remove top item from stack)
– top (get top item without removing it)
– isEmpty
Described as a "Last In First Out"
(LIFO) data structure
CS314 3
Stacks
Implementing a stack
need an underlying collection to hold the elements
of the stack
3 obvious choices?
– native array
– linked structure of nodes
– a list!!!
Adding a layer of abstraction.
A HUGE idea.
array implementation
linked list implementation
https://xkcd.com/2347/
CS314 4
Stacks
Uses of Stacks
The runtime stack used by a
process (running program) to
keep track of methods in
progress
Search problems
Undo, redo, back, forward
CS314 5
Stacks
Stack Operations
Assume a simple stack for integers.
Stack<Integer> s = new Stack<>();
s.push(12);
s.push(4);
s.push( s.top() + 2 );
s.pop();
s.push( s.top() );
//what are contents of stack?
CS314 6
Stacks
Clicker 1 - What is Output?
Stack<Integer> s = new Stack<>();
// put stuff in stack
for (int i = 0; i < 5; i++)
s.push(i);
// Print out contents of stack.
// Assume there is a size method.
for (int i = 0; i < s.size(); i++)
System.out.print(s.pop() + " ");
A 0 1 2 3 4 D 2 3 4
B 4 3 2 1 0 E No output due
C 4 3 2 to runtime error
CS314 7
Stacks
Corrected Version
Stack<Integer> s = new Stack<Integer>();
// put stuff in stack
for (int i = 0; i < 5; i++)
s.push(i);
// print out contents of stack
// while emptying it
final int LIMIT = s.size();
for (int i = 0; i < LIMIT; i++)
System.out.print(s.pop() + " ");
//or
// while (!s.isEmpty())
// System.out.println(s.pop());
CS314 8
Stacks
Stack Operations
Write a method to print out contents of stack
in reverse order.
CS314 9
Stacks
Applications of Stacks
Mathematical Calculations
What does 3 + 2 * 4 equal?
2 * 4 + 3? 3 * 2 + 4?
The precedence of operators affects the
order of operations.
A mathematical expression cannot simply be
evaluated left to right.
A challenge when evaluating a program.
Lexical analysis is the process of
interpreting a program.
What about 1 - 2 - 4 ^ 5 * 3 * 6 / 7 ^ 2 ^ 3
CS314 11
Stacks
Infix and Postfix Expressions
The way we are use to writing
expressions is known as infix
notation
Postfix expression does not
require any precedence rules
3 2 * 1 + is postfix of 3 * 2 + 1
evaluate the following postfix
expressions and write out a
corresponding infix expression:
2324*+* 1234^*+
12-32^3*6/+ 25^1-
CS314 12
Stacks
Clicker Question 2
What does the following postfix expression
evaluate to?
632+*
A. 11
B. 18
C. 24
D. 30
E. 36
CS314 13
Stacks
Evaluation of Postfix Expressions
Easy to do with a stack
given a proper postfix expression:
– get the next token
– if it is an operand push it onto the stack
– else if it is an operator
• pop the stack for the right hand operand
• pop the stack for the left hand operand
• apply the operator to the two operands
• push the result onto the stack
– when the expression has been exhausted the
result is the top (and only element) of the stack
CS314 14
Stacks
Infix to Postfix
Convert the following equations from infix to
postfix:
2^3^3+5*1
11 + 2 - 1 * 3 / 3 + 2 ^ 2 / 3
Problems:
Negative numbers?
parentheses in expression
CS314 15
Stacks
Infix to Postfix Conversion
Requires operator precedence parsing algorithm
– parse v. To determine the syntactic structure of a
sentence or other utterance
Operands: add to expression
Close parenthesis: pop stack symbols until an open
parenthesis appears
Operators:
Have an on stack and off stack precedence
Pop all stack symbols until a symbol of lower
precedence appears. Then push the operator
End of input: Pop all remaining stack symbols and
add to the expression
CS314 16
Stacks
Simple Example
Infix Expression: 3+2*4
PostFix Expression:
Operator Stack:
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 17
Stacks
Simple Example
Infix Expression: +2*4
PostFix Expression: 3
Operator Stack:
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 18
Stacks
Simple Example
Infix Expression: 2*4
PostFix Expression: 3
Operator Stack: +
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 19
Stacks
Simple Example
Infix Expression: *4
PostFix Expression: 3 2
Operator Stack: +
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 20
Stacks
Simple Example
Infix Expression: 4
PostFix Expression: 3 2
Operator Stack: +*
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 21
Stacks
Simple Example
Infix Expression:
PostFix Expression: 3 2 4
Operator Stack: +*
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 22
Stacks
Simple Example
Infix Expression:
PostFix Expression: 3 2 4 *
Operator Stack: +
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 23
Stacks
Simple Example
Infix Expression:
PostFix Expression: 3 2 4 * +
Operator Stack:
Precedence Table
Symbol Off Stack On Stack
Precedence Precedence
+ 1 1
- 1 1
* 2 2
/ 2 2
^ 10 9
( 20 0
CS314 24
Stacks
Example
11 + 2 ^ 4 ^ 3 - ((4 + 5) * 6 ) ^ 2
Show algorithm in action on above equation
CS314 25
Stacks
Balanced Symbol Checking
In processing programs and working with
computer languages there are many
instances when symbols must be balanced
{},[],()
Complications
– when is it not an error to have non matching symbols?
Processing a file
– Tokenization: the process of scanning an input stream.
Each independent chunk is a token.
Tokens may be made up of 1 or more characters
CS314 28
Stacks
Topic 16
Queues
"FISH queue: n.
[acronym, by analogy with FIFO (First In,
First Out)] ‘First In, Still Here’. A joking way of
pointing out that processing of a particular
sequence of events or requests has stopped
dead. Also FISH mode and FISHnet; the
latter may be applied to any network that is
running really slowly or exhibiting extreme
flakiness."
-The Jargon File 4.4.7
Queues
A sharp tool, like stacks
A line
–In England people don’t “get in line”
they “queue up”.
CS314 2
Queues
Queue Properties
Queues are a first in first out data
structure
– FIFO (or LILO, but I guess that sounds a
bit silly)
Add items to the end of the queue
Access and remove from the front
– Access to the element that has been in the
structure the longest amount of time
Used extensively in operating systems
– Queues of processes, I/O requests, and
much more
CS314 3
Queues
Queues in Operating Systems
On a computer with N cores on the CPU, but more
than N processes, how many processes can actually
be executing at one time?
One job of OS, schedule the processes for the CPU
CS314 4
Queues
Queue operations
void enqueue(E item)
– a.k.a. add(E item)
E front()
– a.k.a. E peek()
E dequeue()
– a.k.a. E remove()
boolean isEmpty()
Specify methods in an interface, allow multiple
implementations.
CS314 5
Queues
Queue interface, version 1
public interface Queue314<E> {
//place item at back of this queue
public void enqueue(E item);
CS314 7
Queues
Clicker 1
If implementing a queue with a singly linked list
with references to the first and last nodes (head
and tail) which end of the list should be the front
of the queue in order to have all queue
operations O(1)?
A. The front of the list should be the front of the queue.
B. The back of the list should be the front of the queue.
C. Either end will work to make all ops O(1).
D. Neither end will allow all ops to be O(1).
CS314 8
Queues
Alternate Implementation
How about implementing a Queue with a
native array?
– Seems like a step backwards
CS314 9
Queues
Application of Queues
Radix Sort
– radix is a synonym for base. base 10, base 2
Multi pass sorting algorithm that only looks
at individual digits during each pass
Use queues as buckets to store elements
Create an array of 10 queues
Starting with the least significant digit place
value in queue that matches digit
empty queues back into array
repeat, moving to next least significant digit
CS314 10
Queues
Radix Sort in Action: 1s place
original values in array
9, 113, 70, 86, 12, 93, 37, 40, 252, 7, 79, 12
Look at ones place
9, 113, 70, 86, 12, 93, 37, 40, 252, 7, 79, 12
Array of Queues (all empty initially):
0 5
1 6
2 7
3 8
4 9
CS314 11
Queues
Radix Sort in Action: 1s
original values in array
9, 113, 70, 86, 12, 93, 37, 40, 252, 7, 79, 12
Look at ones place
9, 113, 70, 86, 12, 93, 37, 40, 252, 7, 79, 12
Queues:
0 70, 40 5
1 6 86
2 12, 252, 12 7 37, 7
3 113, 93 8
4 9 9, 79
CS314 12
Queues
Radix Sort in Action: 10s
Empty queues in order from 0 to 9 back into
array
70, 40, 12, 252, 12, 113, 93, 86, 37, 7, 9, 79
Now look at 10's place
70, 40, 12, 252, 12, 113, 93, 86, 37, 7, 9, 79
Queues:
0 7, 9 5 252
1 12, 12, 113 6
2 7 70, 79
3 37 8 86
4 40 9 93
CS314 13
Queues
Radix Sort in Action: 100s
Empty queues in order from 0 to 9 back into array
7, 9, 12, 12, 113, 37, 40, 252, 70, 79, 86, 93
Now look at 100's place
__7, __9, _12, _12, 113, _37, _40, 252, _70, _79, _86, _93
Queues:
0 7, 9, _12, _12, _37, _40, _70, _79, _86, _93 5
1 113 6
2 252 7
3 8
4 9
CS314 14
Queues
Radix Sort in Action: Final Step
Empty queues in order from 0 to 9 back into
array
7, 9, 12, 12, 40, 70, 79, 86, 93, 113, 252
CS314 15
Queues
Radix Sort Code
public static void sort(int[] data){
ArrayList<Queue<Integer>> queues
= new ArrayList<Queue<Integer>>();
for(int i = 0; i < 10; i++)
queues.add(new LinkedList<Integer>());
int passes = numDigits(getMax(data));// helper methods
Big O of Quicksort?
CS314 Fast Sorting 7
private static void swapReferences(Object[] a, int index1, int index2) {
Object tmp = a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}
private void quicksort(Comparable[] data, int start, int stop) {
if(start < stop) {
int pivotIndex = (start + stop) / 2;
// Place pivot at start position
swapReferences(data, pivotIndex, start);
Comparable pivot = data[start];
// Begin partitioning
int j = start;
// from first to j are elements less than or equal to pivot
// from j to i are elements greater than pivot
// elements beyond i have not been checked yet
for(int i = start + 1; i <= stop; i++ ) {
//is current element less than or equal to pivot
if (data[i].compareTo(pivot) <= 0) {
// if so move it to the less than or equal portion
j++;
swapReferences(data, i, j);
}
}
//restore pivot to correct spot
swapReferences(data, start, j);
quicksort( data, start, j - 1 ); // Sort small elements
quicksort( data, j + 1, stop ); // Sort large elements
} // else start >= stop, 0 or 1 element, base case, do nothing
}
Best Worst
A. O(NlogN) O(N2)
B. O(N2) O(N2)
C. O(N2) O(N!)
D. O(NlogN) O(NlogN)
E. O(N) O(NlogN)
CS314 Fast Sorting 9
Clicker 2
Is quicksort always stable?
A. No
B. Yes
When implementing
one temporary array
is used instead of
multiple temporary
arrays.
Why?
times in seconds
CS314 Fast Sorting 18
Comparison of Various Sorts (2011)
Num Items Selection Insertion Quicksort Merge Arrays.sort
1000 0.002 0.001 - - -
2000 0.002 0.001 - - -
4000 0.006 0.004 - - -
8000 0.022 0.018 - - -
16000 0.086 0.070 0.002 0.002 0.002
32000 0.341 0.280 0.004 0.005 0.003
64000 1.352 1.123 0.008 0.010 0.007
128000 5.394 4.499 0.017 0.022 0.015
256000 21.560 18.060 0.035 0.047 0.031
512000 86.083 72.303 0.072 0.099 0.066
1024000 ??? ??? 0.152 0.206 0.138
2048000 0.317 0.434 0.287
4096000 0.663 0.911 0.601
8192000 1.375 1.885 1.246
Comparison of Various Sorts (2020)
Num Selection Insertion Quicksort Mergesort Arrays. Arrays.so Arrays.
rt(Integer) parallelSort
Items sort(int)
1,000 <0.001 <0.001 - - - - -
2,000 0.001 <0.001 - - - - -
4,000 0.004 0.003 - - - - Speeds
8,000 0.017 0.010 - - - - up????
16,000 0.065 0.040 0.002 0.002 0.003 0.011 0.007
32,000 0.258 0.160 0.002 0.003 0.002 0.008 0.003
64,000 1.110 0.696 0.005 0.008 0.004 0.011 0.001
128,000 4.172 2.645 0.011 0.015 0.009 0.024 0.002
256,000 16.48 10.76 0.024 0.034 0.018 0.051 0.004
512,000 70.38 47.18 0.049 0.068 0.040 0.114 0.008
1,024,000 - - 0.098 0.143 0.082 0.259 0.017
2,048,000 - - 0.205 0.296 0.184 0.637 0.035
4,096,000 - - 0.450 0.659 0.383 1.452 0.079
8,192,000 - - 0.941 1.372 0.786 3.354 0.148
Concluding Thoughts
Language libraries often have sorting
algorithms in them
– Java Arrays and Collections classes
– C++ Standard Template Library
– Python sort and sorted functions
Hybrid sorts
– when size of unsorted list or portion of array is
small use insertion sort, otherwise use
O(N log N) sort like Quicksort or Mergesort
Fast Sorting 21
Concluding Thoughts
Sorts still being created!
Timsort (2002)
– created for python version 2.3
– now used in Java version 7.0+
– takes advantage of real world data
– real world data is usually partially sorted,
not totally random
Library Sort (2006)
– Like insertion sort,
but leaves gaps for later elements
Fast Sorting 22
CS314 Fast Sorting 23
Topic 18
Binary Trees
"A tree may grow a
thousand feet tall, but
its leaves will return to
its roots."
-Chinese Proverb
Definitions
A tree is an abstract data type root node
internal
– one entry point, the root nodes
– Each node is either a leaf or an
internal node
– An internal node has 1 or more
children, nodes that can be
reached directly from that
internal node.
– The internal node is said to be
the parent of its child nodes leaf nodes
B C D
E F G H I J
K L M
N O
CS314 Binary Trees 6
Clicker 1
What is the depth of the node that contains
M on the previous slide?
A. 0
B. 1
C. 2
D. 3
E. 4
Clicker 2 - Same tree, same choices
What is the height of the node
that contains D?
CS314 Binary Trees 7
Binary Trees
There are many variations on trees but we
will start with binary trees
binary tree: each node has at most two
children
– the possible children are usually referred to as
the left child and the right child
parent
public BNode();
public BNode(Bnode<E> left, E data,
Bnode<E> right)
public E getData()
public Bnode<E> getLeft()
public Bnode<E> getRight()
Binary Trees 17
Implement Traversals
Implement preorder, inorder, and post order
traversal
– Big O time and space?
Implement a level order traversal using a
queue
– Big O time and space?
Implement a level order traversal without a
queue
– target depth
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
A G X Z
W Q P O U
L K B Z
M R
root
parent
17
< 17 > 17
left child 11 19 right child
50 90 20 78 10 20 28 -25
2 3 5 7 11 13 17
public E getValue()
{ return myData; }
private EmptyBST() {}
private E data;
private BST left;
private BST right;
public NEBST(E d) {
data = d;
right = EmptyBST.getEmptyBST();
left = EmptyBST.getEmptyBST();
}
• Encoding
• Compression
• Huffman Coding
2
Encoding
• UTCS
• 85 84 67 83
• 01010101 01010100 01000011 01010011
3
ASCII - UNICODE
4
Text File
5
Text File???
6
Bitmap and JPEG File
7
Bitmap File????
8
JPEG File
9
JPEG VS BITMAP
• JPEG File
10
Encoding Schemes
11
Why So Many Encoding /
Decoding Schemes?
• Image file formats: bmp, png, jpg, gif, tiff,
svg, cgm, pgm
• Encoding
• Compression
• Huffman Coding
13
Compression
• Compression: Storing the same information
but in a form that takes less memory
• lossless and lossy compression
• Recall:
14
Lossy Artifacts
15
Compression
• 00000000000000000000000000000000
111111111111111111111111111111
• 0 00100000 1 00011110
16
Why Bother?
• Is compression really necessary?
5 Terabytes.
~5,000,000,000,0000 bytes 17
Clicker 1
18
Little Pipes and Big Pumps
Home Internet Access CPU Capability
• 400 Mbps roughly $115 • $2,000 for a good laptop
per month or desktop
• 12 months * 3 years * • Intel® Core™ i9-7900X
$115 = • Assume it lasts 3 years.
• 400,000,000 bits /second • Memory bandwidth
= 5 * 107 bytes / sec 40 GB / sec
= 4.0 * 1010 bytes / sec
• on the order of
6.4 * 1011 instructions /
second
19
Mobile Devices?
Cellular Network iPhone CPU
• Your mileage may vary … • Apple A6 System on a
• Mega bits per second Chip
• AT&T • Coy about IPS
17 mbps download, 7 mbps • 2 cores
upload • Rough estimates:
• T-Mobile & Verizon 1 x 1010 instructions per
12 mbps download, 7 mbps second
upload
• 17,000,000 bits per
second = 2.125 x 106
bytes per second
20
http://tinyurl.com/q6o7wan
Little Pipes and Big Pumps
CPU
Data In
From Network
21
Agenda
• Encoding
• Compression
• Huffman Coding
22
Huffman Coding
• Proposed by Dr. David A. Huffman
– Graduate class in 1951 at MIT with Robert Fano
– term paper or final
– term paper: prove min bits needed for binary
coding of data
– A Method for the Construction of Minimum
Redundancy Codes
• Applicable to many forms of data transmission
– Our example: text files
– still used in fax machines, mp3 encoding, others 23
The Basic Algorithm
27
Building a Tree
Scan the original text
E e r i space
y s n a r l k .
28
Building a Tree
Scan the original text
Eerie eyes seen near lake.
• What is the frequency of each character in the
text?
29
Building a Tree
Prioritize values from file
30
Building a Tree
• The queue after enqueueing all nodes
front back
E i k l y . a n r s sp e
1 1 1 1 1 1 2 2 2 2 4 8
E i k l y . a n r s sp e
1 1 1 1 1 1 2 2 2 2 4 8
33
Building a Tree
k l y . a n r s sp e
1 1 1 1 2 2 2 2 4 8
E i
1 1
34
Building a Tree
k l y . a n r s sp e
2
1 1 1 1 2 2 2 2 4 8
E i
1 1
35
Building a Tree
y . a n r s sp e
2
1 1 2 2 2 2 4 8
E i
1 1
k l
1 1
36
Building a Tree
2
y . a n r s 2 sp e
1 1 2 2 2 2 4 8
k l
E i 1 1
1 1
37
Building a Tree
a n r s 2 2 sp e
2 2 2 2 4 8
k l
E i 1 1
1 1
y .
1 1
38
Building a Tree
a n r s 2 2 sp e
2
2 2 2 2 4 8
E i k l y .
1 1 1 1 1 1
39
Building a Tree
r s 2 sp e
2 2
2 2 4 8
E i k l y .
1 1 1 1 1 1
a n
2 2
40
Building a Tree
r s 2 sp e
2 2 4
2 2 4 8
E i k l y . a n
1 1 1 1 1 1 2 2
41
Building a Tree
2 4 e
2 2 sp
8
4
k l y . a n
E i 1 1 1 1 2 2
1 1
r s
2 2
42
Building a Tree
2 4 4 e
2 2 sp
8
4
k l y . a n r s
E i 1 1 1 1 2 2 2 2
1 1
43
Building a Tree
4 4 e
2 sp
8
4
y . a n r s
1 1 2 2 2 2
2 2
E i k l
1 1 1 1
44
Building a Tree
4 4 4
2 sp e
4 2 2 8
y . a n r s
1 1 2 2 2 2
E i k l
1 1 1 1
45
Building a Tree
4 4 4
e
2 2 8
a n r s
2 2 2 2
E i k l
1 1 1 1
2 sp
4
y .
1 1
46
Building a Tree
4 4 4 6 e
2 sp 8
a n r s 2 2
4
2 2 2 2 y .
E i k l 1 1
1 1 1 1
47
Building a Tree
4 6 e
2 2 2 8
sp
4
E i k l y .
1 1 1 1 1 1
8
4 4
a n r s
2 2 2 2
48
Building a Tree
4 6 e 8
2 2 2 8
sp
4 4 4
E i k l r .
1 1 1 1 1 1
a n r s
2 2 2 2
49
Building a Tree
8
e
8
4 4
10
a n r s
2 2 2 2 4
6
2 2 2 sp
4
E i k l y .
1 1 1 1 1 1
50
Building a Tree
8 10
e
8 4
4 4
6
2 2
a n r s 2 sp
2 2 2 2 4
E i k l y .
1 1 1 1 1 1
Clicker 2 - What is happening to the values with a
low frequency compared to values with a high freq.?
A. Smaller Depth B. Larger Depth
C. Something else
51
Building a Tree
10
16
4
6
2 2 e 8
2 sp 8
4
E i k l y . 4 4
1 1 1 1 1 1
a n r s
2 2 2 2
52
Building a Tree
10 16
4
6
e 8
2 2 8
2 sp
4 4 4
E i k l y .
1 1 1 1 1 1
a n r s
2 2 2 2
53
Building a Tree
26
16
10
4 e 8
6 8
2 2 2 sp 4 4
4
E i k l y .
1 1 1 1 1 1 a n r s
2 2 2 2
54
Building a Tree
•After
enqueueing
26 this node
there is only
16
10 one node left
4 e 8
in priority
6 8 queue.
2 2 2 sp 4 4
4
E i k l y .
1 1 1 1 1 1 a n r s
2 2 2 2
55
Building a Tree
Dequeue the single node
left in the queue. 26
16
This tree contains the 10
new code words for each 4 e 8
character. 6 8
2 2 2 sp 4 4
4
Frequency of root node E i k l y .
a n r s
1 1 1 1 1 1
should equal number of 2 2 2 2
characters in text.
57
Encoding the File
Traverse Tree for Codes
Original Value New Code
E (0100 0101) 0000
i (0110 1001) 0001
k (0110 1011) 0010
l (0110 1100) 0011 26
y (0111 1001) 0100
. (0010 1110) 0101 16
10
space (0010 0000) 011
e (0110 0101) 10 4 e 8
a (0110 0001) 1100 6 8
n (0110 1110) 1101 2 2 2 sp 4 4
r (0111 0010) 1110 4
s (0111 0011) 1111 E i k l y .
1 1 1 1 1 1 a n r s
2 2 2 2
Prefix free codes. The code for a value in never the prefix
of another code.
58
Encoding the File
• Rescan original file and Char New Code
encode file using new code E 0000
words i 0001
Eerie eyes seen near lake. k 0010
l 0011
000010111000011001110 y 0100
010010111101111111010 . 0101
110101111011011001110 space 011
011001111000010100101 e 10
a 1100
n 1101
r 1110
s 1111
59
Encoding the File
Results
61
Clicker 3 - Decoding the File
• Once receiver has tree it
scans incoming bit stream
26
• 0 go left
• 1 go right 10
16
1010001001111000111111
4 e 8
11011100001010 6 8
2 2 2 sp 4 4
A. elk nay sir 4
E i k l y .
1 1 1 1 1 1 a n r s
B. eek a snake 2 2 2 2
C. eek kin sly
D. eek snarl nil
E. eel a snarl
62
Alex Fall 2022
63
Assignment Hints
64
Assignment Example
• "Eerie eyes seen near lake." will result in different
codes than those shown in slides due to:
– adding elements in order to PriorityQueue
– required pseudo eof value (PEOF)
65
Assignment Example
66
Assignment Example
. E i k l y PEOF a n r s SP e
1 1 1 1 1 1 1 2 2 2 2 4 8
67
Assignment Example
i k l y PEOF a n r s SP e
1 1 1 1 1 2 2 2 2 4 8
. E
1 1
68
Assignment Example
i k l y PEOF a n r s 2 SP e
1 1 1 1 1 2 2 2 2 4 8
. E
1 1
69
Assignment Example
l y PEOF a n r s 2 2 SP e
1 1 1 2 2 2 2 4 8
i k
. E 1 1
1 1
70
Assignment Example
PEOF a n r s 2 2 2 SP e
1 2 2 2 2 4 8
i k l y
. E 1 1 1 1
1 1
71
Assignment Example
n r s 2 2 2 SP e
3
2 2 2 4 8
i k l y
. E
PEOF a
1 1 1 1 1
1 1 2
72
Assignment Example
s 2 2 2 SP
3 4 e
2 4
i k 8
l y PEOF a
. E 1 1 n r
1 1 1
2
1 1 2 2
73
Assignment Example
2 2 SP
3 4 4 e
4
i k 8
l y PEOF a
1 1 n r s 2
1 1 1
2
2 2 2
. E
1 1
74
4 4 7 e
4
8
n r s 2
2 2 2
2 2 SP
3
4
. E i k l y
1 1 1 1 1 1 PEOF a
1
2
75
7
4 e 8
8
2 2 SP 4 4
3
4
i k l y n r s
PEOF a 2
1 1 1 1 1 2 2 2
2
. E
1 1
76
e 8 11
8
4 4 4 7
n r s 2 2 2
SP
2 2 2 3 4
i k l y
. E 1 1 1 1 PEOF a
1 1 1 2
77
11 16
e
4 7 8
8
2 2 4 4
SP
3 4
i k l y n r s 2
1 1 1 1 2 2 2
PEOF a
1 2
. E
1 1
78
27
11 16
e
4 7 8
8
2 2 4 4
SP
3 4
i k l y n r s 2
1 1 1 1 2 2 2
PEOF a
1 2
. E
1 1
79
Codes
value: 32, equivalent char: , frequency: 4, new code 011
value: 46, equivalent char: ., frequency: 1, new code 11110
value: 69, equivalent char: E, frequency: 1, new code 11111
value: 97, equivalent char: a, frequency: 2, new code 0101
value: 101, equivalent char: e, frequency: 8, new code 10
value: 105, equivalent char: i, frequency: 1, new code 0000
value: 107, equivalent char: k, frequency: 1, new code 0001
value: 108, equivalent char: l, frequency: 1, new code 0010
value: 110, equivalent char: n, frequency: 2, new code 1100
value: 114, equivalent char: r, frequency: 2, new code 1101
value: 115, equivalent char: s, frequency: 2, new code 1110
value: 121, equivalent char: y, frequency: 1, new code 0011
value: 256, equivalent char: ?, frequency: 1, new code 0100
80
Altering files
• Tower bit map (Eclipse/Huffman/Data).
Alter the first 300 characters of line
16765 to this
~00~00~00~00~00~00~00~00~00~00~00~00~00
~00~00~00~00~00~00~00~00~00~00~00~00~00
~00~00~00~00~00~00~00~00~00~00~00~00~00
~00~00~00~00~00~00~00~00~00~00~00~00~00
~00~00~00~00~00~00~00~00~00~00~00~00~00
~00~00~00~00~00~00~00~00~00~00~00~00~00
~00~00~00~00~00~00~00~00~00~00~00~00~00
~00~00~00~00~00~00~00~00~00 xxx 81
Compression - Why Bother?
• Apostolos "Toli" Lerios
• Facebook Engineer
• Heads image storage group
• jpeg images already
compressed
• look for ways to compress even
more
• 1% less space = millions of
dollars in savings
82
Graphs
Topic 21
" Hopefully, you've played around a bit with The Oracle of Bacon at
Virginia and discovered how few steps are necessary to link just about
anybody who has ever been in a movie to Kevin Bacon, but could there be
some actor or actress who is even closer to the center of the Hollywood
universe?.
By processing all of the almost half of a million people in the Internet
Movie Database I discovered that there are currently 1160 people who are
better centers than Kevin Bacon! … By computing the average of these
numbers we see that the average (Sean) Connery Number is about 2.682
making Connery a better center than Bacon"
-Who is the Center of the Hollywood Universe?,
University of Virginia
That was in 2001.
In 2013 Harvey Keitel has become the center of the Hollywood
Universe. Connery is 136th.
Bacon has moved up to 370th.
An Early Problem in
Graph Theory
Leonhard Euler (1707 - 1783)
– One of the first mathematicians to study graphs
The Seven Bridges of Konigsberg Problem
– Konigsberg is now called Kaliningrad
A puzzle for the residents of the city
The river Pregel flows through the city
7 bridges crossed the river
Can you cross all bridges while crossing
each bridge only once? An Eulerian Circuit
CS314 Graphs 2
Konigsberg and the River Pregel
B
D
CS314 Graphs 3
Clicker 1
How many solutions does the Seven Bridges
of Konigsberg Problem have?
A. 0
B. 1
C. 2
D. 3
E. >= 4
CS314 Graphs 4
How to Solve
Brute Force?
Euler's Solution
– Redraw the map as a graph
(really a multigraph as opposed
to a simple graph, 1 or 0 edges
per pair of vertices)
a
b d
c
CS314 Graphs 5
Euler's Proposal
A connected graph has an Euler tour (cross
every edge exactly one time and end up at
starting node) if and only if every vertex has
an even number of edges
– Eulerian Circuit
Clicker 2 - What if we reduce the problem to
only crossing each edge (bridge) exactly
once?
– Doesn't matter if we end up where we started
– Eulerian Trail
A. 0 B. 1 C. 2 D. 3 E. >= 4
CS314 Graphs 6
Graph Definitions
A graph is comprised of a set of vertices
(nodes) and a set of edges (links, arcs)
connecting the vertices
– An edge connects 2 vertices
in a directed graph edges are one-way
– movement allowed from first node to second, but
not second to first
– directed graphs also called digraphs
in an undirected graph edges are two-way
– movement allowed in either direction
CS314 Graphs 7
Definitions
In a weighted graph the edge has cost or weight
that measures the cost of traveling along the edge
A path is a sequence of vertices connected by
edges
– The path length is the number of edges
– The weighted path length is the sum of the cost of the
edges in a path
A cycle is a path of length 1 or more that starts and
ends at the same vertex without repeating any
other vertices
– a directed acyclic graph is a directed graph with
no cycles
CS314 Graphs 8
Graphs We've Seen
12 35
3 16 21 56
CS314 Graphs 9
Example Graph
Scientists (and academics of ALL kinds) use
graphs to model all kinds of things.
CS314 Graphs 11
Roman
Transportation Network
CS314 Graphs 12
Example Graph
US Airport Network
CS314 Graphs 14
Example Graph
CS314 Graphs 15
Example Graph
"Jefferson" High School, Ohio Chains of Affection: The Structure of Adolescent Romantic
and Sexual Networks, 2005,
Representing Graphs
How to store a graph as a data structure?
CS314 Graphs 17
Adjacency Matrix
Representation Country Code
A Br Bl Ch Co E FG G Pa Pe S U V
Argentina A
A 0 1 1 1 0 0 0 0 1 0 0 1 0
Brazil Br
Br 1 0 1 0 1 0 1 1 1 1 1 1 1
Bl 1 1 0 1 0 0 0 0 1 1 0 0 0 Bolivia Bl
Ch 1 0 1 0 0 0 0 0 0 1 0 0 0 Chile Ch
Co 0 1 0 0 0 1 0 0 0 1 0 0 1 Colombia Co
E 0 0 0 0 1 0 0 0 0 1 0 0 0 Ecuador E
FG 0 1 0 0 0 0 0 0 0 0 1 0 0 French
FG
Guiana
G 0 1 0 0 0 0 0 0 0 0 1 0 1 Guyana G
Pa 1 1 1 0 0 0 0 0 0 0 0 0 0 Paraguay Pa
Pe 0 1 1 1 1 1 0 0 0 0 0 0 0
Peru Pe
S 0 1 0 0 0 0 1 1 0 0 0 0 0
Suriname S
U 1 1 0 0 0 0 0 0 0 0 0 0 0
V 0 1 0 0 1 0 0 1 0 0 0 0 0 Uruguay U
Venezuela V
CS314 Graphs 18
Undirected Graph?
Use a ragged 2d array to save space
CS314 Graphs 19
The Map Coloring Problem
How many colors do you need to color a
map, so that no 2 countries that have a
common border (not a point) are colored the
same?
How to solve using Brute Force?
CS314 Graphs 20
Example
Source: https://en.wikipedia.org/wiki/Four_color_theorem 21
A Solution Blue
Blue Yellow
Yellow
Green
Blue Green
Yellow
Red
Green
Blue
Yellow
CS314 Graphs 22
What About the Ocean?
A Br Bl Ch Co E FG G Pa Pe S U V Oc
A 0 1 1 1 0 0 0 0 1 0 0 1 0 1
Br 1 0 1 0 1 0 1 1 1 1 1 1 1 1
Bl 1 1 0 1 0 0 0 0 1 1 0 0 0 0
Ch 1 0 1 0 0 0 0 0 0 1 0 0 0 1
Co 0 1 0 0 0 1 0 0 0 1 0 0 1 1
E 0 0 0 0 1 0 0 0 0 1 0 0 0 1
FG 0 1 0 0 0 0 0 0 0 0 1 0 0 1
G 0 1 0 0 0 0 0 0 0 0 1 0 1 1
Pa 1 1 1 0 0 0 0 0 0 0 0 0 0 0
Pe 0 1 1 1 1 1 0 0 0 0 0 0 0 1
S 0 1 0 0 0 0 1 1 0 0 0 0 0 1
U 1 1 0 0 0 0 0 0 0 0 0 0 0 1
V 0 1 0 0 1 0 0 1 0 0 0 0 0 1
Oc 1 1 0 1 1 1 1 1 0 1 1 1 1 0
CS314 Graphs 23
Make the Ocean Blue
Red Yellow
Yellow Red
Green Red
Green
Yellow
Blue
Blue
Green Red Blue
Yellow
CS314 Graphs 24
More Definitions
A dense graph is one with a "large" number
of edges
– maximum number of edges?
A "sparse" graph is one in which the number
of edges is "much less" than the maximum
possible number of edges
– No standard cutoff for dense and sparse graphs
CS314 Graphs 25
Graph Representation
For dense graphs the adjacency matrix is a
reasonable choice
– For weighted graphs change booleans to double
or int
– Can the adjacency matrix handle
directed graphs?
Most graphs are sparse, not dense
For sparse graphs an adjacency list is an
alternative that uses less space
Each vertex keeps a list of edges to the
vertices it is connected to.
CS314 Graphs 26
Graph Implementation
public class Graph
private static final double INFINITY
= Double.MAX_VALUE;
private Map<String, Vertex> vertices;
CS314 Graphs 28
Vertex Class (nested in Graph)
private static class Vertex
private String name;
private List<Edge> adjacent;
public Vertex(String n)
CS314 Graphs 29
Edge Class (nested in Graph)
private static class Edge
private Vertex dest;
private double cost;
CS314 Graphs 30
Unweighted Shortest Path
Given a vertex, S (for start) find the shortest
path from S to all other vertices in the graph
Graph is unweighted (set all edge costs to 1)
V1 V7
S V6
V2
V4
V8
V3
V5
CS314 Graphs 31
6 Degrees of Wikipedia
https://www.sixdegreesofwikipedia.com/
CS314 Graphs 32
Word Ladders
Agree upon dictionary
silly
Start word and end word of
same length
sully
sulky
Change one letter at a time to
form step hulky
Step must also be a word
hunky
funky
Example: Start = silly, end =
funny funny
CS314 Graphs 33
Clicker 3 - Graph Representation
What are the vertices and when does
an edge exist between two vertices?
Vertices Edges
A. Letters Words
B. Words Words that share one or more letters
C. Letters Words that share one or more letters
D. Words Words that differ by one letter
E. Words Letters
CS314 Graphs 34
smarm
swart
smart
start
smalt
scart
Portion of Graph
CS314 Graphs 35
Clicker 4 - Size of Graph
Number of vertices and edges depends on dictionary
Modified Scrabble dictionary, 5 letter words
Words are vertices
– 8660 words, 7915 words that are one letter different from
at least one other word
Edge exists between words if they are one letter
different
– 24,942 edges
Is this graph sparse or dense?
A. Sparse Max number of edges =
B. Dense N * (N - 1) / 2
CS314 Graphs 37,493,470 36
Clicker 5 - Unweighted Shortest
Path Algorithm
Problem: Find the shortest word ladder
between two words if one exists
What kind of search should we use?
CS314 Graphs 37
Unweighted Shortest Path Algorithm
Set distance of start to itself to 0
Create a queue and add the start vertex
while the queue is not empty
– remove front
– loop through all edges of current vertex
• get vertex edge connects to
• if this vertex has not been visited (have not found path
to the destination of the edge)
– sets its distance to current distance + 1
– sets its previous vertex to current vertex
– add new vertex to queue
CS314 Graphs 38
smarm
swart
smart
start
smalt
scart
Portion of Graph
CS314 Graphs 39
smarm
swart
smart
start
smalt
scart
smalt
scart
smalt
scart
smalt
scart
smalt
scart
smalt
scart
smalt
scart
smalt
scart
smalt
scart
smalt
scart
smalt
scart
CS314 Graphs 52
Dijkstra on Creating the Algorithm
What is the shortest way to travel from Rotterdam to Groningen, in
general: from given city to given city. It is the algorithm for the
shortest path, which I designed in about twenty minutes. One
morning I was shopping in Amsterdam with my young fiancée, and
tired, we sat down on the café terrace to drink a cup of coffee and I
was just thinking about whether I could do this, and I then designed
the algorithm for the shortest path. As I said, it was a twenty-minute
invention. In fact, it was published in ’59, three years later. The
publication is still readable, it is, in fact, quite nice. One of the
reasons that it is so nice was that I designed it without pencil
and paper. I learned later that one of the advantages of designing
without pencil and paper is that you are almost forced to avoid all
avoidable complexities. Eventually that algorithm became, to my
great amazement, one of the cornerstones of my fame.
— Edsger Dijkstra, in an interview with Philip L. Frana,
Communications of the ACM, 2001 (wiki page on the algorithm)
Vertex Class (nested in Graph)
private static class Vertex
private String name;
private List<Edge> adjacent;
public Vertex(String n)
CS314 Graphs 54
Dijkstra's Algorithm
Pick the start vertex
Set the distance of the start vertex to 0 and all
other vertices to INFINITY
While there are unvisited vertices:
– Let the current vertex be the vertex with the lowest cost
path from start to it that has not yet been visited
– mark current vertex as visited
– for each edge from the current vertex
• if the sum of the cost of the current vertex and the cost of the
edge is less than the cost of the destination vertex
– update the cost of the destination vertex
– set the previous of the destination vertex to the current vertex
– enqueue this path (not vertex) to the priority queue
– THIS IS NOT VISITING THE NEIGHBORING VERTEX
55
Dijkstra's Algorithm
Example of a Greedy Algorithm
– A Greedy Algorithm does what appears to be the
best thing at each stage of solving a problem
Gives best solution in Dijkstra's Algorithm
Does NOT always lead to best answer
Fair teams:
– (10, 10, 8, 8, 8), 2 teams
Making change with fewest coins
(1, 5, 10) 15 cents
(1, 5, 12) 15 cents
CS314 Graphs 56
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
Clicker 6 - What is the cost of the lowest
cost path from A to E?
A. 5
B. 17
C. 20
D. 28 57
E. 37
7 C 3
∞
3 F
∞
4
B 21
1 ∞
D 6
A ∞
E
0
∞
17 5
G
A is start vertex ∞
G
∞
[(A,0)] pq
dequeue (A,0)
Mark A as visited
59
7 C 3
∞
3 F
∞
4
B 21
1 ∞
D 6
A ∞
E
0 ∞
17 5
[ ] pq
G∞
current vertex A:
loop through A's edges
if sum of cost from A to dest is less than current cost
update cost and prev 60
7 C 3
7
3 F
∞
4
B 21
1 ∞
D 6
A ∞
E
0
∞
17 5
[ ] pq
G
A -> C, 0 + 7 < INFINITY ∞
[(C,7)] pq
61
7 C 3
7
3 F
∞
4
B 21
1 1
D 6
A ∞
E
0 ∞
17 5
[(C,7)] pq
G∞
A -> B, 0 + 1 < INFINITY
[(B,1), (C, 7)] pq (Note, the (B,1) jumps in front of (C,7)
62
7 C 3
7
3 F∞
4
B 21
1 1
D 6
A ∞
E
0 ∞
17 5
[(B,1), (C, 7)] pq
G
A -> G, 0 + 17 < INFINITY 17
63
7 C 3
7
3 F
∞
4
B 21
1 1
D 6
A ∞
E
0 ∞
17 5
[(B,1), (C, 7), (G, 17)] pq
G
current vertex B: 17
G
[(C, 4), (C, 7), (G, 17)] pq 17
G
17
[(C, 4), (C, 7), (G, 17), (D, 22)] pq
current vertex is C, cost 4
loop through C's edges 67
7 C 3
4
3 F
∞
4
B 21
1 1
D 6
A 22
E
0 ∞
17 5
G
17
[(C, 7), (G, 17), (D, 22)] pq
C -> A, 7 + 4 !< 0, skip
68
7 C 3
4
3 F
∞
4
B 21
1 1
D 6
A 22
E
0 ∞
17 5
G
17
[(C, 7), (G, 17), (D, 22)] pq
C -> B, 4 + 3 !< 1, skip
69
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 22
E
0 ∞
17 5
G
17
[(C, 7), (G, 17), (D, 22)] pq
C -> F, 4 + 3 < INFINITY
[(C, 7), (F, 7), (G, 17), (D, 22)] pq 70
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 22
E
0 ∞
17 5
G
17
[(C, 7), (F, 7), (G, 17), (D, 22)] pq
current vertex is C
Already visited so skip 71
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 22
E
0 ∞
17 5
G
17
[(F, 7), (G, 17), (D, 22)] pq
current vertex is F
loop through F's edges 72
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 22
E
0 ∞
17 5
G
17
[(G, 17), (D, 22)] pq
F -> C, 7 + 3 !< 4, so skip
73
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 ∞
17 5
Vertex Vertex
name G name D
distance 17 distance 22 76
Lower Cost Path to D
New, lower cost path to D. Alter Vertex D's
distance to 11 and add to priority queue
[ , , ]
Vertex Vertex
name G name D
distance 17 distance 11
PROBLEMS?????
Abstractly [(D, 11), (G, 17), (D, 11)] 77
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 ∞
17 5
G
[(D, 11), (G, 17), (D, 22)] pq 17
current vertex is D
loop through D's edges
78
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 ∞
17 5
G
[(G, 17), (D, 22)] pq 17
79
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 17
17 5
G
[(G, 17), (D, 22)] pq 17
G
[ (G, 17), (E, 17), (D, 22)] pq 17
81
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 17
17 5
G
[(G, 17), (E, 17), (D, 22)] pq 16
D -> G, 11 + 5 < 17
update G's cost and previous
[(G, 16), (G, 17), (E, 17), (D, 22)] pq 82
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 17
17 5
G
[(G, 17), (E, 17), (D, 22)] pq 16
current vertex is G
loop though edges, already visited all neighbors
83
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 17
17 5
G
[(E, 17), (D, 22)] pq 16
current vertex is E
loop though edges, already visited all neighbors
84
7 C 3
4
3 F
7
4
B 21
1 1
D 6
A 11
E
0 17
17 5
No unvisited vertices. G
16
Each Vertex stores cost (distance) of lowest cost
path from start Vertex to itself and previous vertex
in path from start vertex to itself.
85
Alternatives to Dijkstra's Algorithm
A*, pronounced "A Star"
A heuristic, goal of finding shortest weighted path
from single start vertex to goal vertex
Uses actual distance like Dijkstra's but also
estimates remaining cost or distance
– distance is set to current distance from start PLUS the
estimated distance to the goal
For example when finding a path between towns,
estimate the remaining distance as the straight-line
(as the crow flies) distance between current
location and goal.
CS314 Graphs 86
Spanning Tree
Spanning Tree: A tree of edges that
connects all the vertices in a graph
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
Clicker 7 -
Minimum Spanning Tree
Minimum Spanning Tree: A spanning tree in
a weighted graph with the lowest total cost
used in network design, taxonomy, Image registration,
and more!
Cost of spanning
7 C 3 tree shown?
3 A. 6
F
B. 7
4 C. 29
B 21 D. 61
1
D 6 E. None of These
A E
17 5
G 88
Prim's Algorithm
Initially created by Vojtěch Jarník
Rediscovered by Prim (of Sweetwater, TX)
and Dijkstra
Pick a vertex arbitrarily from graph
– In other words, it doesn't matter which one
Add lowest cost edge between the tree and
a vertex that is not part of the tree UNTIL
every vertex is part of the tree
Greedy Algorithm, very similar to Dijkstra's
CS314 Graphs 89
Prim's Algorithm
2
A B
4 11
3
2
C D E
2 7
8 4 6
5
F G
1
Pick D as root
CS314 Graphs 90
Prim's Algorithm
2
A B
4 11
3
2
C D E
2 7
8 4 6
5
F G
1
Lowest cost edge from tree to vertex not in Tree?
2 from D to A (or C)
CS314 Graphs 91
Prim's Algorithm
2
A B
4 11
3
2
C D E
2 7
8 4 6
5
F G
1
Lowest cost edge from tree to vertex not in Tree?
2 from D to C (OR from A to B)
CS314 Graphs 92
Prim's Algorithm
2
A B
4 11
3
2
C D E
2 7
8 4 6
5
F G
1
Lowest cost edge from tree to vertex not in Tree?
2 from A to B
CS314 Graphs 93
Prim's Algorithm
2
A B
4 11
3
2
C D E
2 7
8 4 6
5
F G
1
Lowest cost edge from tree to vertex not in Tree?
5 from D to G
CS314 Graphs 94
Prim's Algorithm
2
A B
4 11
3
2
C D E
2 7
8 4 6
5
F G
1
Lowest cost edge from tree to vertex not in Tree?
1 from G to F
CS314 Graphs 95
Prim's Algorithm
2
A B
4 11
3
2
C D E
2 7
8 4 6
5
F G
1
Lowest cost edge from tree to vertex not in Tree?
6 from G to E
CS314 Graphs 96
Prim's Algorithm
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
Pick D as root
CS314 Graphs 97
Prim's Algorithm
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
7 C 3
3 F
4
B 21
1
D 6
A E
17 5
G
5/17/1971
555389085
Manchester, VT
12
"Mike Scott" hash
[email protected] function
"Kelly" "Olivia"
"Isabelle"
134 Megabytes
CS314 Hash Tables 14
Hash Function
SHA 512 Hash code
0 1 2 3 .........177............ 996
"Isabelle"
CS314 Hash Tables 24
Handling Collisions
What to do when inserting an element and
already something present?
CS314 3
Red Black Trees
Red Black Trees
A BST with more complex algorithms to
ensure balance
Each node is labeled as Red or Black.
Path: A unique series of links (edges)
traverses from the root to each node.
– The number of edges (links) that must be
followed is the path length
In Red Black trees paths from the root to
elements with 0 or 1 child are of particular
interest
CS314 4
Red Black Trees
Paths to Single or Zero Child
Nodes
How many? 19
12 35
3 16 21 56
CS314 5
Red Black Trees
Red Black Tree Rules
1. Is a binary search tree
2. Every node is colored either red or
black
3. The root of the whole tree is black
4. If a node is red its children must be
black. (a.k.a. the red rule)
5. Every path from a node to a null link
must contain the same number of black
nodes (a.k.a. the path rule)
CS314 6
Red Black Trees
Example of a Red Black Tree
The root of a Red Black tree is black
Every other node in the tree follows these rules:
– Rule 3: If a node is Red, all of its children are Black
– Rule 4: The number of Black nodes must be the same in all paths
from the root node to null nodes
19
12 35
3 16 21 56
30
CS314 7
Red Black Trees
Red Black Tree?
19
12 35
50
0
75
-10
-5 135
CS314 8
Red Black Trees
Clicker 2
Is the tree on the previous slide a binary
search tree? Is it a red black tree?
BST? Red-Black?
A. No No
B. No Yes
C. Yes No
D. Yes Yes
CS314 9
Red Black Trees
Red Black Tree?
19
12 35
3 16
Perfect?
Full?
Complete?
CS314 10
Red Black Trees
Clicker 3
Is the tree on the previous slide a binary
search tree? Is it a red black tree?
BST? Red-Black?
A. No No
B. No Yes
C. Yes No
D. Yes Yes
CS314 11
Red Black Trees
Implications of the Rules
If a Red node has any children, it must have
two children and they must be Black. (Why?)
If a Black node has only one child that child
must be a Red leaf. (Why?)
Due to the rules there are limits on how
unbalanced a Red Black tree may become.
– on the previous example may we hang a new
node off of the leaf node that contains 0?
CS314 12
Red Black Trees
Properties of Red Black Trees
If a Red Black Tree is complete, with all
Black nodes except for Red leaves at the
lowest level the height will be minimal, ~log N
To get the max height for N elements there
should be as many Red nodes as possible
down one path and all other nodes are Black
– This means the max height would b approximately
2 * log N (don't use this as a formula)
– typically less than this
– see example on next slide
– interesting exercise, draw max height tree with N nodes
Max Height Red Black Tree
14
12 35
13 21 56
1
43 99
15 25
80 100
14 nodes, height 5
70
CS314 14
Red Black Trees
Maintaining the Red Black
Properties in a Tree
Insertions
Must maintain rules of Red Black Tree.
New Node always a leaf
– can't be black or we will violate rule 4
– therefore the new leaf must be red
– If parent is black, done (trivial case)
– if parent red, things get interesting because a red
leaf with a red parent violates rule 3
CS314 15
Red Black Trees
Insertions with Red Parent - Child
Must modify tree when insertion would result in
Red Parent - Child pair using color changes and
rotations.
30
15 70
20 60 85
10
80 90
50 65
5
CS314
40 55 16
Red Black Trees
Case 1
Suppose sibling of parent is Black.
– by convention null nodes are black
In the previous tree, true if we are inserting a
3 or an 8.
– What about inserting a 99? Same case?
Let X be the new leaf Node, P be its Red
Parent, S the Black sibling and G, P's and
S's parent and X's grandparent
– What color is G?
CS314 17
Red Black Trees
Case 1 - The Picture
G
P S
C D E
X
A B
P S
C D E
X
A B
If X is an outside node a single
rotation between P and G fixes the problem.
A rotation is an exchange of roles between a parent
and child node. So P becomes G's parent. Also must
recolor P and G.
CS314 19
Red Black Trees
Single Rotation
P
X G
A B C
S
D E
Apparent rule violation?
Recall, S is null if X is a leaf, so no problem
If this occurs higher in the tree (why?) subtrees A, B,
and C will have one more black node than D and E.
CS314 20
Red Black Trees
Case 2
What if X is an inside node relative to G?
– a single rotation will not work
Must perform a double rotation
– rotate X and P
– rotate X and G G
P S
A D E
X
B C
CS314 21
Red Black Trees
First Rotation
Rotate P and X, no color change
X S
P C D E
A B
P G
A B C
S
D E
CS314 23
Red Black Trees
Case 3
Sibling is Red, not Black
G
P S
C D E
X
A B
Any problems?
CS314 24
Red Black Trees
Fixing Tree when S is Red
Must perform single rotation between parent,
P and grandparent, G, and then make
appropriate color changes
P
X G
B C S
A
D E
CS314 25
Red Black Trees
More on Insert
Problem: What if on the previous example
G's parent (GG!) had been red?
Easier to never let Case 3 ever occur!
On the way down the tree, if we see a node X that
has 2 Red children, we make X Red and its two
children black.
– if recolor the root, recolor it to black
– the number of black nodes on paths below X remains
unchanged
– If X's parent was Red then we have introduced 2
consecutive Red nodes.(violation of rule)
– to fix, apply rotations to the tree, same as inserting node
CS314 26
Red Black Trees
Example of Inserting Sorted Numbers
1 2 3 4 5 6 7 8 9 10
Insert 1. A leaf so
red. Realize it is
1
root so recolor
to black.
CS314 27
Red Black Trees
Insert 2
make 2 red. Parent
1
is black so done.
2
CS314 28
Red Black Trees
Insert 3
1 3
CS314 29
Red Black Trees
Insert 4
On way down see
2 with 2 red children.
2
Recolor 2 red and
children black.
1 3 2
1 3
2
When adding 4
parent is black 1 3
so done.
Set root to black! 4
CS314 30
Red Black Trees
Insert 5
5's parent is red. 2
Parent's sibling is
black (null). 5 is 3
1
outside relative to
grandparent (3) so rotate 4
parent and grandparent then
recolor
5
CS314 31
Red Black Trees
Finish insert of 5
1 4
3 5
CS314 32
Red Black Trees
Insert 6
On way down see
4 with 2 red 2
children. Make
4 red and children 1 4
black. 4's parent is
black so no problem. 3 5
CS314 33
Red Black Trees
Finishing insert of 6
3 5
CS314 34
Red Black Trees
Insert 7
CS314 35
Red Black Trees
Finish insert of 7
1 4
3 6
5 7
CS314 36
Red Black Trees
Insert 8
The caveat!!!
Getting unbalanced 2
on that right subtree?!?
1 4
On way down see 6
with 2 red children. 3 6
Make 6 red and
children black. This 5 7
creates a problem
because 6's parent, 4, is
also red. Must perform
rotation.
CS314 37
Red Black Trees
Still Inserting 8
2
Recolored now
need to
rotate. 1 4
3 6
Recall, the subtrees
and the one extra
5 7
black node.
CS314 38
Red Black Trees
Finish inserting 8
Result of
rotation 4
2 6
1 3 5 7
CS314 39
Red Black Trees
Insert 9
2 6
1 3 5 7
CS314 40
Red Black Trees
Finish Inserting 9
2 6
1 3 5 8
7 9
After rotations and recoloring
CS314 41
Red Black Trees
Insert 10
2 6
1 3 5 8
CS314 42
Red Black Trees
Insert 11
4
2 6
1 3 5 8
7 9
Again a rotation is
needed. 10
11
CS314 43
Red Black Trees
Finish inserting 11
4
2 6
1 3 5 8
7 10
9 11
CS314 44
Red Black Trees
Topic 24
Heaps
CS314 Heaps 4
Example Min Heap
12
17 15
19 52 37 25
45 21
CS314 Heaps 5
Add Operation
Add new element to next open spot in array
Swap with parent if new value is less
than parent
Continue back up the tree as long as the
new value is less than new parent node
CS314 Heaps 6
Add Example
Add 15 to heap (initially next left most node)
12
17 15
19 52 37 25
45 21 15
CS314 Heaps 7
Add Example
Swap 15 and 52
12
17 15
19 15 37 25
45 21 52
CS314 Heaps 8
Enqueue Example
Swap 15 and 17, then stop
12
15 15
19 17 37 25
45 21 52
CS314 Heaps 9
Add Example
Insert the following values 1 at a time into a
min heap:
16 9 5 8 13 8 8 5 5 19 27 9 3
CS314 Heaps 10
Internal Storage
Interestingly heaps are often implemented
with an array instead of nodes
for element at index i:
12
parent index: i / 2
17 15 left child index: i * 2
right child index: i * 2 + 1
19 52 37 25
45 21
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
12 17 15 19 52 37 25 45 21
CS314 Heaps 11
In Honor of
Elijah,
The Meme King,
Spring 2020
CS314 Heaps 12
PriorityQueue Class
public class PriorityQueue<E extends Comparable<? super E>>
{
public PriorityQueue() {
con = getArray(2);
}
CS314 Heaps 13
PriorityQueue enqueue / add
public void enqueue(E val) {
if ( size >= con.length - 1 )
enlargeArray(con.length * 2);
size++;
int indexToPlace = size;
while ( indexToPlace > 1
&& val.compareTo( con[indexToPlace / 2] ) < 0 ) {
19 52 37 25
45 21 15 10 / 2 = 5 (index of parent)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
12 17 15 19 52 37 25 45 21 15
Enqueue Example
With Array Shown
Swap 15 and 52
12
17 15
19 15 37 25
45 21 52
5 / 2 = 2 (index of parent)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
12 17 15 19 15 37 25 45 21 52
Enqueue Example
With Array Shown
Swap 15 and 17
12
15 15
19 17 37 25
45 21 52
2 / 2 = 1 (index of parent)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
12 15 15 19 17 37 25 45 21 52
Enqueue Example
With Array Shown
15 !< 12 -> DONE
12
15 15
19 17 37 25
45 21 52
2 / 1 = 1 (index of parent)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
12 15 16 19 17 37 25 45 21 52
Remove -> remove 12
12
15 15
19 17 37 25
45 21 52
CS314 Heaps 19
Remove / Dequeue
min value / front of queue is in root of tree
swap value from last node to root and move
down swapping with smaller child unless
values is smaller than both children
CS314 Heaps 20
Dequeue Example
Swap 35
into root 12
(save 12
to return) 15 13
17 23 45 53
45 21 35
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
12 15 13 17 23 45 53 45 21 35
Dequeue Example
Swap 35
into root 35
(save 12
to return) 15 13
17 23 45 53
45 21
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
35 15 13 17 23 45 53 45 21
Dequeue Example
Min child?
35 1 * 2 = 2 -> 15
1 * 2 + 1 = 3 -> 13
15 13 Swap with 13
17 23 45 53
45 21
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
35 15 13 17 23 45 53 45 21
Dequeue Example
13
15 35
17 23 45 53
45 21
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
13 15 35 17 23 45 53 45 21
Dequeue Example
Min child?
13 3 * 2 = 6 -> 45
3 * 2 + 1 = 7 -> 53
15 35 Less than or equal to
both of my children!
Stop!
17 23 45 53
45 21
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
13 15 35 17 23 45 53 45 21
Dequeue Code
public E dequeue( ) {
E top = con[1];
int hole = 1;
boolean done = false;
while ( hole * 2 < size && ! done ) {
int child = hole * 2;
// see which child is smaller
if ( con[child].compareTo( con[child + 1] ) > 0 )
child++; // child now points to smaller
Sound familiar?
Recursion?
N! = 1 for N == 0
N! = N * (N - 1)! for N > 0
Recursive Solution?
static {
lookupTable = new ArrayList<>();
lookupTable.add(null);
lookupTable.add(ONE);
lookupTable.add(ONE);
CS314 } Dynamic Programming 15
Fibonacci Memoization
public static BigInteger fib(int n) {
// check lookup table
if (n < lookupTable.size()) {
return lookupTable.get(n);
}
Weight
3 4 1 0.25
4 4 12 3.0
Limit = 8 5 6 19 3.167
6 7 12 1.714
int result = 0;
if (current < items.size()) {
// don't use item
int withoutItem
= knapsack(items, current + 1, capacity);
int withItem = 0;
// if current item will fit, try it
Item currentItem = items.get(current);
if (currentItem.weight <= capacity) {
withItem += currentItem.value;
withItem += knapsack(items, current + 1,
capacity - currentItem.weight);
}
result = Math.max(withoutItem, withItem);
}
return result;
}
Knapsack - Dynamic Programming
Recursive backtracking starts with max
capacity and makes choice for items:
choices are:
– take the item if it fits
– don't take the item
Dynamic Programming, start with
simpler problems
Reduce number of items available
… AND Reduce weight limit on knapsack
Creates a 2d array of possibilities
CS314 Dynamic Programming 28
Knapsack - Optimal Function
OptimalSolution(items, weight) is best
solution given a subset of items and a weight
limit
2 options:
OptimalSolution does not select ith item
– select best solution for items 1 to i - 1with weight
limit of w
OptimalSolution selects ith item
– New weight limit = w - weight of ith item
– select best solution for items 1 to i - 1with new
weight limit 29
Knapsack Optimal Function
OptimalSolution(items, weight limit) =
0 if 0 items
For item = 1 to N
for weight = 1 to WeightLimit
if(weight of ith item > weight)
M[item, weight] = M[item - 1, weight]
else
M[item, weight] = max of
M[item - 1, weight] AND
value of item + M[item - 1, weight - weight of item]
Knapsack - Table Item
1
Weight
1
Value
6
2 2 11
3 4 1
4 4 12
5 6 19
6 7 12
items / capacity 0 1 2 3 4 5 6 7 8
{} 0 0 0 0 0 0 0 0 0
{1}
{1,2}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5}
{1,CS314
2, 3, 4, 5, 6} Dynamic Programming 33
Knapsack - Completed Table
items / weight 0 1 2 3 4 5 6 7 8
{}
0 0 0 0 0 0 0 0 0
{1}
[1, 6]
0 6 6 6 6 6 6 6 6
{1,2}
[2, 11]
0 6 11 17 17 17 17 17 17
{1, 2, 3}
[4, 1]
0 6 11 17 17 17 17 18 18
{1, 2, 3, 4}
[4, 12]
0 6 11 17 17 18 23 29 29
{1, 2, 3, 4, 5}
[6, 19]
0 6 11 17 17 18 23 29 30
{1, 2, 3, 4, 5, 6}
CS314
[7, 12]
0 6Dynamic
11Programming
17 17 18 23 29 3430
Knapsack - Items to Take
items / weight 0 1 2 3 4 5 6 7 8
{}
0 0 0 0 0 0 0 0 0
{1}
[1, 6]
0 6 6 6 6 6 6 6 6
{1,2}
[2, 11]
0 6 11 17 17 17 17 17 17
{1, 2, 3}
[4, 1]
0 6 11 17 17 17 17 17 17
{1, 2, 3, 4}
[4, 12]
0 6 11 17 17 18 23 29 29
{1, 2, 3, 4, 5}
[6, 19]
0 6 11 17 17 18 23 29 30
{1, 2, 3, 4, 5, 6}
CS314
[7, 12]
0 6Dynamic
11Programming
17 17 18 23 29 3530
Dynamic Knapsack
// dynamic programming approach
public static int knapsack(ArrayList<Item> items, int maxCapacity) {
final int ROWS = items.size() + 1;
final int COLS = maxCapacity + 1;
int[][] partialSolutions = new int[ROWS][COLS];
// first row and first column all zeros
CS314 Tries 2
Tries aka Prefix Trees
Pronunciation:
From retrieval
Name coined by Computer Scientist
Edward Fredkin
Retrieval so “tree”
… but that is very confusing so most people
pronounce it “try”
CS314 Tries 3
Predictive Text and AutoComplete
Search engines and texting applications
guess what you want after typing only a few
characters
CS314 Tries 4
AutoComplete
So do other programs such as IDEs
CS314 Tries 5
Searching a Dictionary
How?
Could search a set for all values that start
with the given prefix.
Naively O(N) (search the whole data
structure).
Could improve if possible to do a binary
search for prefix and then localize search to
that location.
CS314 Tries 6
Tries
A general tree (more than 2 children possible)
Root node (or possibly a list of root nodes)
Nodes can have many children
– not a binary tree
In simplest form each node stores a character
and a data structure (list?) to refer to its
children
"Stores" all the words or phrases
in a dictionary.
How?
CS314 Tries 7
René de la Briandais Original Paper
CS314 Tries 8
????
CS314 Tries 9
????
Picture of a Dinosaur
CS314 Tries 10
Fall 2022 - Ryan P.
Created with Procreate: https://procreate.art/
CS314 Tries 11
Can
CS314 Tries 12
Candy
CS314 Tries 13
Fox
CS314 Tries 14
Clicker 2
Is “fast” in the dictionary represented by this
Trie?
A. No
B. Yes
C. It depends
CS314 Tries 15
Clicker 3
Is “fist” in the dictionary represented by this
Trie?
A. No
B. Yes
C. It depends
CS314 Tries 16
Tries
Another example
of a Trie
Each node stores:
– A char
– A boolean
indicating if the
string ending at
that node is a word
– A list of children
CS314 Tries 17
Predictive Text and AutoComplete
As characters are entered
we descend the Trie
… and from the current
node …
… we can descend to
terminators and leaves to
see all possible words
based on current prefix
b, e, e -> bee, been, bees
CS314 Tries 18
Tries
Stores words and
phrases.
– other values
possible, but typically
Strings
The whole word or
phrase is not actually
stored in a
single node.
… rather the path in
the tree represents
the word.
Implementing a Trie
public class Trie {
public Trie() {
root = new TNode();
numNodes = 1;
CS314 Tries 20
TNode Class
private static class TNode {
private boolean word;
private char ch;
private LinkedList<TNode> children;
CS314 Tries 21
Basic Operations
Adding a word to the Trie
Getting all words with given prefix
Demo in IDE
CS314 Tries 22
Compressed Tries
Some words, especially long ones, lead to a
chain of nodes with single child, followed by
single child:
b s
e t
e i u
l o
a l d o y
c p
l
r l y
k
Compressed Trie
Reduce number of nodes, by having nodes
store Strings
A chain of single child followed by single
child (followed by single child … ) is
compressed to a single node with that String
Does not have to be a chain that terminates
in a leaf node
– Can be an internal chain of nodes
CS314 Tries 24
Original, Uncompressed
b s
e t
e i u
l o
a l d s y
c p
l
r l y
k
CS314 Tries 25
Compressed Version
b s
ell to
e id u
ck p
ar ll sy y
CS314 Tries 26
Data Structures
Data structures we have studied
– arrays, array based lists, linked lists, maps, sets,
stacks, queues, trees, binary search trees,
graphs, hash tables, red-black trees, priority
queues, heaps, tries
Most program languages have some built in
data structures, native or library
Must be familiar with performance of data
structures
– best learned by implementing them yourself
CS314 Heaps 27
Data Structures
We have not covered every data structure
Heaps
http://en.wikipedia.org/wiki/List_of_data_structures
Data Structures
deque, b-trees, quad-trees, binary space
partition trees, skip list, sparse list, sparse
matrix, union-find data structure, Bloom
filters, AVL trees, 2-3-4 trees, and more!
Must be able to learn new and apply new
data structures
CS314 Heaps 29
Topic 27
Functional Programming
Functional Programming with Java 8
• 2. First-class functions
• 4. Function closures
3
Effect-free code (19.1)
• side effect: A change to the state of an object or program
variable produced by a call on a function (i.e., a method).
– example: modifying the value of a variable
– example: printing output to System.out
– example: reading/writing data to a file, collection, or network
6
Lambda expressions
• lambda expression ("lambda"): Expression that describes a
function by specifying its parameters and return value.
– Java 8 adds support for lambda expressions.
– Essentially an anonymous function (aka method)
• Syntax:
(parameters ) -> expression
• Example:
(x) -> x * x // squares a number
•GACK!!!
•How do we generalize the idea of "add or
subtract"?
– How much work would it be to add
other operators?
– Can functional programming help remove the
repetitive code?
9
Code w/ lambdas
• We can represent the math operation as a lambda:
10
getMat method
private MathMatrix getMat(MathMatrix rhs,
IntBinaryOperator operator) {
// IntBinaryOperator Documentation
11
Clicker 1
•Which of the following is a lambda
that checks if x divides evenly into y?
A. (x, y) -> y / x == 0
B. (x, y) -> x / y == 0
C. (x, y) -> y % x == 0
D. (x, y) -> x % y == 0
E. (x, y) -> y * x == 0
12
Streams (19.3)
• stream: A sequence of elements from a data source that
supports aggregate operations.
14
The map modifier
• The map modifier applies a lambda to each stream element:
– higher-order function: Takes a function as an argument.
• Abstracting away loops (and data structures)
17
The reduce modifier
• The reduce modifier (method) combines elements of a stream
using a lambda combination function.
– Accepts two parameters: an initial value and a lambda to combine
that initial value with each subsequent value in the stream.
18
Stream operators
Method name Description
anyMatch(f) returns true if any elements of stream match given predicate
allMatch(f) returns true if all elements of stream match given predicate
22
Optional results fix
• To extract the optional result, use a "get as" terminator.
– Converts type OptionalInt to Integer
23
Ramya, Spring 2018
•“Okay, but why?”
•Programming with Streams is an
alternative to writing out the
loops ourselves
•Streams “abstract away” the loop
structures we have spent so much
time writing
•Why didn’t we just start with these?
24
Stream exercises
• Write a method sumAbsVals that uses stream operations to
compute the sum of the absolute values of an array of
integers. For example, the sum of {-1, 2, -4, 6, -9} is
22.
25
Closures (19.4)
• bound/free variable: In a lambda expression, parameters
are bound variables while variables in the outer containing
scope are free variables.
• function closure: A block of code defining a function along
with the definitions of any free variables that are defined in the
containing scope.
27
Method references
ClassName::methodName
28
Streams and lists
• A collection can be converted into a stream by calling its
stream method:
29
Streams and strings
output:
word set = [not, be, or, to]
30
Streams and files
stream operations:
Files.lines -> ["haiku are funny",
"but sometimes they don't make sense",
"refrigerator"]
-> mapToInt -> [15, 35, 12]
-> max -> 35
31
Stream exercises
• Write a method fiveLetterWords that accepts a file name as
a parameter and returns a count of the number of unique lines
in the file that are exactly five letters long. Assume that each
line in the file contains at least one word.
• Write a method using streams that finds and prints the first 5
perfect numbers. (Recall a perfect number is equal to the sum
of its unique integer divisors, excluding itself.)
32