Presentation is loading. Please wait.

Presentation is loading. Please wait.

CISH 4960 Introduction to Programming Lecture 101 Introduction to Programming Lecture 10 Recursion/Data Structures Tom Blough

Similar presentations


Presentation on theme: "CISH 4960 Introduction to Programming Lecture 101 Introduction to Programming Lecture 10 Recursion/Data Structures Tom Blough"— Presentation transcript:

1 CISH 4960 Introduction to Programming Lecture 101 Introduction to Programming Lecture 10 Recursion/Data Structures Tom Blough blought@rh.edu www.rh.edu/~blought/cish4960 860.618.4148 CISH 4960 Fall 2002

2 CISH 4960 Introduction to Programming Lecture 102 Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems Chapter 11 focuses on: –thinking in a recursive manner –programming in a recursive manner –the correct use of recursion –recursion examples

3 CISH 4960 Introduction to Programming Lecture 103 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word, a recursive definition is often not helpful But in other situations, a recursive definition can be an appropriate way to express a concept Before applying recursion to programming, it is best to practice thinking recursively

4 CISH 4960 Introduction to Programming Lecture 104 Recursive Definitions Consider the following list of numbers: 24, 88, 40, 37 Such a list can be defined as A LIST is a: number or a: number comma LIST That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST The concept of a LIST is used to define itself

5 CISH 4960 Introduction to Programming Lecture 105 Recursive Definitions The recursive part of the LIST definition is used several times, terminating with the non- recursive part: number comma LIST 24, 88, 40, 37 number comma LIST 88, 40, 37 number comma LIST 40, 37 number 37

6 CISH 4960 Introduction to Programming Lecture 106 Infinite Recursion All recursive definitions have to have a non- recursive part If they didn't, there would be no way to terminate the recursive path Such a definition would cause infinite recursion This problem is similar to an infinite loop, but the non-terminating "loop" is part of the definition itself The non-recursive part is often called the base case

7 CISH 4960 Introduction to Programming Lecture 107 Recursive Definitions N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive This definition can be expressed recursively as: 1! = 1 N! = N * (N-1)! The concept of the factorial is defined in terms of another factorial Eventually, the base case of 1! is reached

8 CISH 4960 Introduction to Programming Lecture 108 Recursive Definitions 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 1 6 24 120 2

9 CISH 4960 Introduction to Programming Lecture 109 Recursive Programming A method in Java can invoke itself; if set up that way, it is called a recursive method The code of a recursive method must be structured to handle both the base case and the recursive case Each call to the method sets up a new execution environment, with new parameters and local variables As always, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself)

10 CISH 4960 Introduction to Programming Lecture 1010 Recursive Programming Consider the problem of computing the sum of all the numbers between 1 and any positive integer N This problem can be recursively defined as: i = 1 N N-1 i = 1 N-2 = N + = N + (N-1) + = etc.

11 CISH 4960 Introduction to Programming Lecture 1011 Recursive Programming main sum sum(3) sum(1) sum(2) result = 1 result = 3 result = 6

12 CISH 4960 Introduction to Programming Lecture 1012 Recursive Programming Note that just because we can use recursion to solve a problem, doesn't mean we should For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version You must carefully decide whether recursion is the correct technique for any problem

13 CISH 4960 Introduction to Programming Lecture 1013 Indirect Recursion A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which in turn invokes m1 again This is called indirect recursion, and requires all the same care as direct recursion It is often more difficult to trace and debug

14 CISH 4960 Introduction to Programming Lecture 1014 Indirect Recursion m1m2m3 m1m2m3 m1m2m3

15 CISH 4960 Introduction to Programming Lecture 1015 Maze Traversal We can use recursion to find a path through a maze From each location, we can search in each direction Recursion keeps track of the path through the maze The base case is an invalid move or reaching the final destination See MazeSearch.java (page 611) See Maze.java (page 612)

16 CISH 4960 Introduction to Programming Lecture 1016 Towers of Hanoi The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller ones on top The goal is to move all of the disks from one peg to another under the following rules: –We can move only one disk at a time –We cannot move a larger disk on top of a smaller one

17 CISH 4960 Introduction to Programming Lecture 1017 Towers of Hanoi An iterative solution to the Towers of Hanoi is quite complex A recursive solution is much shorter and more elegant See SolveTowers.java (page 618) See TowersOfHanoi.java (page 619)

18 CISH 4960 Introduction to Programming Lecture 1018 Data Structures We can now explore some advanced techniques for organizing and managing information Chapter 12 focuses on: –dynamic structures –Abstract Data Types (ADTs) –linked lists –queues –stacks

19 CISH 4960 Introduction to Programming Lecture 1019 Static vs. Dynamic Structures A static data structure has a fixed size This meaning is different than those associated with the static modifier Arrays are static; once you define the number of elements it can hold, it doesn’t change A dynamic data structure grows and shrinks as required by the information it contains

20 CISH 4960 Introduction to Programming Lecture 1020 Object References Recall that an object reference is a variable that stores the address of an object A reference can also be called a pointer They are often depicted graphically: student John Smith 40725 3.57

21 CISH 4960 Introduction to Programming Lecture 1021 References as Links Object references can be used to create links between objects Suppose a Student class contained a reference to another Student object John Smith 40725 3.57 Jane Jones 58821 3.72

22 CISH 4960 Introduction to Programming Lecture 1022 References as Links References can be used to create a variety of linked structures, such as a linked list: studentList

23 CISH 4960 Introduction to Programming Lecture 1023 Abstract Data Types An abstract data type (ADT) is an organized collection of information and a set of operations used to manage that information The set of operations define the interface to the ADT As long as the ADT accurately fulfills the promises of the interface, it doesn't really matter how the ADT is implemented Objects are a perfect programming mechanism to create ADTs because their internal details are encapsulated

24 CISH 4960 Introduction to Programming Lecture 1024 Abstraction Our data structures should be abstractions That is, they should hide details as appropriate We want to separate the interface of the structure from its underlying implementation This helps manage complexity and makes the structures more useful

25 CISH 4960 Introduction to Programming Lecture 1025 Intermediate Nodes The objects being stored should not have to deal with the details of the data structure in which they may be stored For example, the Student class stored a link to the next Student object in the list Instead, we can use a separate node class that holds a reference to the stored object and a link to the next node in the list Therefore the internal representation actually becomes a linked list of nodes

26 CISH 4960 Introduction to Programming Lecture 1026 Book Collection Let’s explore an example of a collection of Book objects The collection is managed by the BookList class, which has an private inner class called BookNode Because the BookNode is private to BookList, the BookList methods can directly access BookNode data without violating encapsulation See MagazineRack.java (page 641) See MagazineList.java (page 642) See Magazine.java (page 644)

27 CISH 4960 Introduction to Programming Lecture 1027 Other Dynamic List Implementations It may be convenient to implement as list as a doubly linked list, with next and previous references: list

28 CISH 4960 Introduction to Programming Lecture 1028 Other Dynamic List Implementations It may also be convenient to use a separate header node, with references to both the front and rear of the list count: 4 front rear list

29 CISH 4960 Introduction to Programming Lecture 1029 Queues A queue is similar to a list but adds items only to the end of the list and removes them from the front It is called a FIFO data structure: First- In, First-Out Analogy: a line of people at a bank teller’s window enqueue dequeue

30 CISH 4960 Introduction to Programming Lecture 1030 Queues We can define the operations on a queue as follows: –enqueue - add an item to the rear of the queue –dequeue - remove an item from the front of the queue –getFront – return the object at the front of the queue, but do not remove it from the queue –isEmpty - returns true if the queue is empty –clear – removes all items from the queue As with our linked list example, by storing generic Object references, any object can be stored in the queue Queues are often helpful in simulations and any processing in which items get “backed up”

31 CISH 4960 Introduction to Programming Lecture 1031 Side Effects in Functions Note the Queue ADT had dequeue and getFront Methods can be divided into two types –Commands – modify objects –Queries – return information about objects Queries that change objects are said to have “side effects” There are mathematical reasons for not allowing side effects in programming – referential transparency In layman’s terms – “Asking a question should not change the answer” getFront can be called repeatedly and return the same result each time until a command method is called

32 CISH 4960 Introduction to Programming Lecture 1032 Stacks A stack ADT is also linear, like a list or queue Items are added and removed from only one end of a stack It is therefore LIFO: Last-In, First-Out Analogy: a stack of plates

33 CISH 4960 Introduction to Programming Lecture 1033 Stacks Stacks are often drawn vertically: poppush

34 CISH 4960 Introduction to Programming Lecture 1034 Stacks Some stack operations: –push - add an item to the top of the stack –pop - remove an item from the top of the stack –getTop - retrieves the top item without removing it –isEmpty - returns true if the stack is empty –clear – removes all items from the stack The java.util package contains a Stack class, which is implemented using a Vector See Decode.java (page 649)

35 CISH 4960 Introduction to Programming Lecture 1035 Trees vs. Linked List Linked list -- collection of nodes where each node references only one neighbor Tree -- also collection of nodes, but each node may reference multiple neighbors

36 CISH 4960 Introduction to Programming Lecture 1036 Trees Trees can be used to model hierarchical organization of data

37 CISH 4960 Introduction to Programming Lecture 1037 Trees A is the root node B is the parent of D and E D and E are children of B (C \ F) is an edge 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 are external nodes, or leaves (i.e., nodes with no children) A, B, C, D, E, F, G, H, I are internal nodes depth (level) of E is 2 (number of edges to root) height of the tree is 3 (max number of edges) degree of node B is 2 (number of children)

38 CISH 4960 Introduction to Programming Lecture 1038 Graph definitions There are two kinds of graphs: directed graphs (sometimes called digraphs) and undirected graphs Birmingham Rugby London Cambridge Bristol Southhampton Dover 60 140 190 150 100 120 110 An undirected graph start fill pan with water take egg from fridge break egg into pan boil water add salt to water A directed graph

39 CISH 4960 Introduction to Programming Lecture 1039 Graph Terminology A graph is a collection of nodes (or vertices) and edges (or arcs) –Each node contains an element –Each edge connects two nodes together (or possibly the same node to itself) and may contain an edge attribute A directed graph is one in which the edges have a direction An undirected graph is one in which the edges do not have a direction –Note: Whether a graph is directed or undirected is a logical distinction—it describes how we think about the graph –Depending on the implementation, we may or may not be able to follow a directed edge in the “backwards” direction

40 CISH 4960 Introduction to Programming Lecture 1040 Collection Classes The Java 2 platform contains a Collections API This group of classes represent various data structures used to store and manage objects Their underlying implementation is implied in the class names, such as ArrayList and LinkedList Several interfaces are used to define operations on the collections, such as List, Set, SortedSet, Map, and SortedMap

41 CISH 4960 Introduction to Programming Lecture 1041 Recursion Example 1/16 3/16 5/16 7/16 9/16 11/16 13/16 15/16 1/8 3/8 5/8 7/8 1/4 3/4 1/2 0 1

42 CISH 4960 Introduction to Programming Lecture 1042 Data Structure Example Back Front Queue Queue Interface: –void enqueue( object obj) –void dequeue() –object getFront() –boolean isEmpty() –void clear()


Download ppt "CISH 4960 Introduction to Programming Lecture 101 Introduction to Programming Lecture 10 Recursion/Data Structures Tom Blough"

Similar presentations


Ads by Google