Lecture 10: Algorithms and
Data Structures
What You Will Learn Today
- A recursive method is a method which calls itself.
- A complex case is reduced to a slightly simpler case.
- The method stops calling itself when it reaches a base case (a
simple, trivial, special case).
- Recursive helper methods can be used, making a slight change to the
original problem.
- Indirect or mutual recursion occurs when two or more methods call
each other.
- Infinite recursion occurs if the method does not simplify, or the
trivial case is not reached.
- A StackOverflowError will be thrown and the program will terminate.
Advantages |
Disadvantages |
- Can be shorter and easier to design and code
- Can better model how we think of the problem
|
- More method calls uses more stack space and memory
- May run slower (usually not much)
|
Recursive Problem-Solving Steps
- Consider various ways for simplifying inputs.
- Combine solutions with simpler inputs into solution to the original
problem.
- Find special-case solutions to the simplest inputs.
- Implement by combining simple cases and reduction steps.
- If not a special case, use a reduction step. (Usually handle special
cases first.)
- Test with different inputs including invalid ones
- e.g. in the example below, using
n==1
instead of n<=1
would cause infinite recursion for factorial(0)
.
Factorial
|
Iterative |
Recursive |
Method
Code |
int factorial (int n)
{
int fact = 1;
for (int i = 2; i <= n; i++)
fact *= i;
return fact;
} |
int factorial (int n)
{
if (n <= 1) // not n == 1
return 1;
else
return n * factorial(n - 1);
} |
Example
n=3 |
i |
fact |
2 |
2 * 1 = 2 |
3 |
3 * 2 = 6 |
|
factorial(3)
= 3 * factorial(2)
= 3 * 2 * factorial(1)
= 3 * 2 * 1
= 3 * 2
= 6 |
Greatest Common Divisor
In mathematics, the greatest common divisor is the largest number
which can divide two numbers exactly (with no remainder/modulus)
int gcd (int a, int b)
{
if (b < a) return gcd(b, a);
if (b % a == 0) return a;
else return gcd(b, b % a);
}
Example: gcd (12, 20) = gcd (12, 20 % 12) = gcd (12, 8) = gcd (8, 12) = gcd
(8, 12 % 8) = gcd (8, 4) = gcd (4, 8) = 4. Check: 12/4=3, 20/4=5
gcd (60, 105) = ?
gcd (396, 144) = ?
Towers of Hanoi
- The Towers of Hanoi game is constructed with n discs and 3 pegs (A, B, C).
- Goal: move all n discs from peg A to peg C, using peg B
- Constraints: move only the top disc; do not put smaller disc on
larger disc
- Recursive algorithm (pseudocode):
if n=1 then
Move disc 1 from frompeg to topeg
else
Move n-1 discs frompeg to temppeg (using topeg)
Move disc n from frompeg to topeg
Move n-1 discs temppeg to topeg (using frompeg)
Traversing a Maze
- Create a two-dimensional m-by-n array filled with 1s and 0s, with a 1 in
the upper left and lower right corners
- Start in the upper left corner (0, 0)
- The maze is solved when reaching the lower right corner (m-1, n-1)
- Follow 1s horizontally (left/right) or vertically (up/down)
- traverse(x+1,y); traverse (x-1, y); traverse(x, y+1); traverse(x, y-1);
- If the cell is out of the matrix or already marked with a 0, return false
- Otherwise mark the cell as visited e.g. with a 3
- Mark the final path e.g. with a 7
A Few Other Applications of Recursion
- power(x, n) and sumfirst(n) can be written recursively like
factorial(n) using the n-1th term.
- Using recursion for computing the fibonacci numbers (2, 3, 5, 8,
13, 21, etc.) is much slower than using iteration.
- To test if a sentence is a palindrome (reads the same forward and
backward): test if first and last letters are the same.
- To generate all 2n subsets of a set: include or remove
one element, then recursively find subsets of these two sets.
- To generate all 2n permutations of a set: put each
element first, then find permutations of each remaining subset.
- Many searching and sorting algorithms use recursion.
- A list is an element, an element plus a list (e.g. lisp
programming language), or two smaller lists.
- Traversing (processing) all elements in a tree (hierarchical
structure) by recursively traversing each branch.
- Compilers and calculators parse the syntax of an expression like
(3 + 4) * 5
- A fractal is a recursively defined graphic (see the j2sdk demo
applet Fractal, Lewis & Loftus Ch. 11, or my interactive
fractals applet)
- A collection is an object that stores other objects.
- e.g. A Vector object can store, add and remove objects.
- Collections can be
- ordered (sorted) or unordered (unsortable)
- homogeneous (all the same) or heterogeneous (a mix)
- See the Java Tutorial trail on collections.
- An abstract data type (ADT) hides the implementation of a data
structure.
- ADTs separate interface from implementation.
- ADTs are reusable and reliable.
- Objects are used to make ADTs.
- Data and methods to manipulate the data are encapsulated inside
the object.
Dynamic Data Structures
- Dynamic data structures can grow and shrink dynamically. Their size
is not predetermined.
- They have methods to add and remove data elements.
- A linked list is a group of Node objects. Each node contains
data and a pointer to the next node.
- There also needs to be a pointer to the front of the list. The last node
points to null.
- To insert and delete nodes, change their pointers.
- Nodes can be implemented as inner classes.
- There are several types of linked lists.
- Doubly-linked lists also have pointers to previous elements.
- Lists can store pointers to both head and tail (a double ended queue or
deque).
- The tail of a circular list points to its head.
- A LinkedList class and List interface are defined in java.util.
- LinkedList has many methods to retrieve, add and remove elements.
- Linked lists can be used as stacks, queues or double ended queues.
- A stack is a last-in, first-out linear data structure.
- Items are put onto and removed from the top of the stack only.
- Stacks are used by the Java virtual machine (and the operating system) to
store method calls.
- When a method is called, its parameters are pushed on the stack.
- When a method returns, the parameters are popped from the stack.
- A Stack class is defined in java.util.
- Stack extends Vector and implements List.
- Methods include void push(Object item), Object pop(),
Object peek() and boolean empty().
- A queue is a first-in, first-out linear data structure.
- Items go into the rear of the queue and are removed from the
front.
- Methods can include void enqueue(item), item dequeue(),
boolean empty().
- Sorting algorithms put unordered items into sequential order (e.g.
alphabetic, numeric, size, date).
- Criteria for choosing a sorting algorithm include simplicity,
efficiency, memory use, and data types.
- Bubble sort (O(n2)): Swap successive elements if the
lower element has larger value than the higher element.
- Selection sort (O(n2)): Find smallest value, put in
first position, find next smallest, put in second position, etc.
- Insertion sort (O(n2)): Insert each value into a
previously sorted subset of the list.
- Merge sort (O(n log n)): Cut the array in half, recursively sort
each half, then merge the sorted halves.
- Quick sort (O(n log n)): Partition into low and high elements, then
recursively sort each partition.
- The Arrays class has built-in
sort()
methods based on
quick sort and merge sort.
- To sort an array of objects, the objects should implement the
Comparable interface.
- Generic algorithms are powerful because they can work on a
variety of data.
- The Collections class contains sort methods that can sort array
lists.
- See the j2sdk demo applet SortDemo to compare speed of bubble sort,
bidirectional bubble sort and quick sort.
- Searching algorithms find an item in a previously sorted array or
list.
- Sequential search (O(n)) requires testing each element in an array.
- Binary search (O(log n)) determines whether the value is in the
first or second half, then recursively searches that half.
- The Arrays class has built-in
binarySearch()
methods.
To Do After Class
-
Lab 8 and
Project 2 Design Specification
are due Friday. Lab 9 and
Homework 5 are due next Friday.
-
Readings/References: Horstmann Ch. 17, 18, 19; Lewis & Loftus Ch.
6.3, 11, 12; Deitel & Deitel Ch. 17
-
Electronic Resources: Java Tutorial: Collections, SDK demo
applets: Fractal, SortDemo, GraphLayout.