Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Algorithms in Java IT310 Data Structures and Algorithms ( in Java) Seminar 4 Instructor : Vladimir Gubanov, PhD

Similar presentations


Presentation on theme: "Data Structures and Algorithms in Java IT310 Data Structures and Algorithms ( in Java) Seminar 4 Instructor : Vladimir Gubanov, PhD"— Presentation transcript:

1 Data Structures and Algorithms in Java IT310 Data Structures and Algorithms ( in Java) Seminar 4 Instructor : Vladimir Gubanov, PhD Email : vgubanov@kaplan.eduvgubanov@kaplan.edu AIM : vladimirg77

2 Data Structures and Algorithms in Java Stacks, Queues and Recursion

3 Stacks3 Abstract Data Types (ADTs)  An abstract data type (ADT) is an abstraction of a data structure  An ADT specifies: Data stored Operations on the data Error conditions associated with operations  Example: ADT modeling a simple stock trading system The data stored are buy/sell orders The operations supported are  order buy(stock, shares, price)  order sell(stock, shares, price)  void cancel(order) Error conditions:  Buy/sell a nonexistent stock  Cancel a nonexistent order Abstract data types allow to delay the specific implementation of a data type until it is understood what operations are required to operate on the data. Only after the list of the required operations is determined - possible possible implementations are to be discussed

4 Stacks 4

5 What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack).

6 Data Structures and Algorithms in Java 6 Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data A stack is called an LIFO structure: last in/first out

7 Stacks7 The Stack ADT  The Stack ADT stores arbitrary objects  Insertions and deletions follow the last-in first- out scheme  Think of a spring-loaded plate dispenser  Main stack operations: push(object): inserts an element object pop(): removes and returns the last inserted element  Auxiliary stack operations: object top(): returns the last inserted element without removing it integer size(): returns the number of elements stored boolean isEmpty(): indicates whether no elements are stored

8 Push (ItemType newItem) Function: Adds newItem to the top of the stack. Preconditions: Stack has been initialized and is not full. Postconditions: newItem is at the top of the stack.

9 Pop (ItemType& item) Function: Removes topItem from stack and returns it in item. Preconditions: Stack has been initialized and is not empty. Postconditions: Top element has been removed from stack and item is a copy of the removed element.

10

11 Data Structures and Algorithms in Java 11 Stacks (continued) Figure 4-1 A series of operations executed on a stack Generally, the stack is very useful in situations when data have to be stored and then retrieved in reverse order.

12 Stacks12 Stack Interface in Java  Java interface corresponding to our Stack ADT  Requires the definition of class EmptyStackException  Different from the built-in Java class java.util.Stack public interface Stack { public int size(); public boolean isEmpty(); public E top() throws EmptyStackException; public void push(E element); public E pop() throws EmptyStackException; }

13 Stacks13 Exceptions  Attempting the execution of an operation of ADT may sometimes cause an error condition, called an exception  Exceptions are said to be “thrown” by an operation that cannot be executed  In the Stack ADT, operations pop and top cannot be performed if the stack is empty  Attempting the execution of pop or top on an empty stack throws an EmptyStackException © 2010 Goodrich, Tamassia

14 Stacks14 Applications of Stacks  Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine  Indirect applications Auxiliary data structure for algorithms Component of other data structures © 2010 Goodrich, Tamassia

15 Stacks15 Method Stack in the JVM  The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack. Each JVM thread has a Java stack containing all currently active methods(only one method can be active – others are suspended)  When a method is called, the JVM pushes on the stack a frame containing Local variables and return value Program counter, keeping track of the statement being executed  When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack  Each method frame includes and operand stack (source of arguments and repository of results) main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { … } bar PC = 1 m = 6 foo PC = 3 j = 5 k = 6 main PC = 2 i = 5 © 2010 Goodrich, Tamassia

16 Stacks16 Array-based Stack  A simple way of implementing the Stack ADT uses an array  We add elements from left to right  A variable keeps track of the index of the top element S 012 t … Algorithm size() return t + 1 Algorithm pop() if isEmpty() then throw EmptyStackException else t  t  1 return S[t + 1] © 2010 Goodrich, Tamassia Stack methods have to be implemented. Flexible array can be used (p.146 of your textbook). When the stack exceeds the initial size of the array – a copy to a larger array is created.

17 Stacks17 Array-based Stack (cont.)  The array storing the stack elements may become full  A push operation will then throw a FullStackException Limitation of the array- based implementation Not intrinsic to the Stack ADT S 012 t … Algorithm push(o) if t = S.length  1 then throw FullStackException else t  t + 1 S[t]  o © 2010 Goodrich, Tamassia

18 Stacks18 Performance and Limitations  Performance Let n be the number of elements in the stack The space used is O(n) Each operation (popping and pushing) is executed in the constant time O(1)  Limitations The maximum size of the stack is defined a priori and cannot be changed without copying to a larger array (O(n) then) Trying to push a new element into a full stack causes an implementation-specific exception © 2010 Goodrich, Tamassia

19 Other Implementations of Stack  Can be implemented in ArrayList  Can be implemented in Linked List  Implementation: Includes creating and proper object (of above) Defining pop(), push(), isEmpty(), topEl(), clear() methods see p. Fig 4.4 (p.146) of the textbook for ArrayList ( in next two slides), Fig 4.5 (p.147) for Linked List No need to define the stack size in advance 19Stacks

20 Data Structures and Algorithms in Java 20 ArrayList Stack Implementation Figure 4-4 Array list implementation of a stack

21 Data Structures and Algorithms in Java 21 Stacks (continued) Figure 4-4 Array list implementation of a stack (continued)

22 Stacks22 HTML Tag Matching The Little Boat The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage. Will the salesman die? What color is the boat? And what about Naomi? The Little Boat The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage. 1. Will the salesman die? 2. What color is the boat? 3. And what about Naomi? For fully-correct HTML, each should pair with a matching © 2010 Goodrich, Tamassia

23 Stacks23 Evaluating Arithmetic Expressions 14 – 3 * 2 + 7 = (14 – (3 * 2) ) + 7 Operator precedence * has precedence over +/– Associativity operators of the same precedence group evaluated from left to right Example: (x – y) + z rather than x – (y + z) Idea: push each operator on the stack, but first pop and perform higher and equal precedence operations.

24 Stacks24 Quadratic Algorithm Algorithm spans1(X, n) Input array X of n integers Output array S of spans of X # S  new array of n integers n for i  0 to n  1 don s  1n while s  i  X[i  s]  X[i] 1  2  …  (n  1) s  s  11  2  …  (n  1) S[i]  s n return S 1 Algorithm spans1 runs in O(n 2 ) time © 2010 Goodrich, Tamassia

25 Stacks25 Linear Algorithm Algorithm spans2(X, n) # S  new array of n integers n A  new empty stack 1 for i  0 to n  1 don while (  A.isEmpty()  X[A.top()]  X[i] ) don A.pop()n if A.isEmpty() then n S[i]  i  1n else S[i]  i  A.top()n A.push(i)n return S 1 Each index of the array Is pushed into the stack exactly one Is popped from the stack at most once The statements in the while-loop are executed at most n times Algorithm spans2 runs in O(n) time © 2010 Goodrich, Tamassia

26 Stacks in java.util package  Available as generic stack – extension of Vector class  Can be created and initialized as : java.util.Stack stack = new java.util.Stack();  Has five methods ( empty(), peek(), pop(), push(Object el), search(Object el), Stack()  Elements can be accessed not at one end only – violation of stack integrity © 2010 Goodrich, Tamassia26Stacks

27 Data Structures and Algorithms in Java 27 Stacks in java.util Figure 4-7 A list of methods in java.util.Stack ; all methods from Vector are inherited

28 Queues28 Queues © 2010 Goodrich, Tamassia

29 What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: –Elements are added at one end. –Elements are removed from the other end. The element added first is also removed first (FIFO: First In, First Out). queue elements enter no changes of order elements exit 2341 tailhead

30 Data Structures and Algorithms in Java 30 Queues A queue is a waiting line that grows by adding elements to its end and shrinks by taking elements from its front A queue is a structure in which both ends are used: –One for adding new elements –One for removing them A queue is an FIFO structure: first in/first out

31 Data Structures and Algorithms in Java 31 Queue Operations The following operations are needed to properly manage a queue: –clear() — Clear the queue –isEmpty() — Check to see if the queue is empty –enqueue(el) — Put the element el at the end of the queue –dequeue() — Take the first element from the queue –firstEl() — Return the first element in the queue without removing it

32 Queue Specification Definitions: (provided by the user) –MAX_ITEMS: Max number of items that might be on the queue –ItemType: Data type of the items on the queue Operations –MakeEmpty –Boolean IsEmpty –Boolean IsFull –Enqueue (ItemType newItem) –Dequeue (ItemType& item) (serve and retrieve)

33 Queues33 The Queue ADT  The Queue ADT stores arbitrary objects  Insertions and deletions follow the first-in first-out scheme  Insertions are at the rear of the queue and removals are at the front of the queue  Main queue operations: enqueue(object): inserts an element at the end of the queue object dequeue(): removes and returns the element at the front of the queue  Auxiliary queue operations: object front(): returns the element at the front without removing it integer size(): returns the number of elements stored boolean isEmpty(): indicates whether no elements are stored  Exceptions Attempting the execution of dequeue or front on an empty queue throws an EmptyQueueException © 2010 Goodrich, Tamassia

34 Enqueue (ItemType newItem) Function: Adds newItem to the rear of the queue. Preconditions: Queue has been initialized and is not full. Postconditions: newItem is at rear of queue.

35 Dequeue (ItemType& item) Function: Removes front item from queue and returns it in item. Preconditions: Queue has been initialized and is not empty. Postconditions: Front element has been removed from queue and item is a copy of removed element.

36 Data Structures and Algorithms in Java 36 Queues (continued) Figure 4-8 A series of operations executed on a queue In the difference from Stack, changes need to be monitored at the beginning of the queue and at the end : elements are engueued on one end (right above) and dequeued on the other ( left above).

37 Queues37 Annother Example OperationOutputQ enqueue(5)–(5) enqueue(3)–(5, 3) dequeue()5(3) enqueue(7)–(3, 7) dequeue()3(7) front()7(7) dequeue()7() dequeue()“error”() isEmpty()true() enqueue(9)–(9) enqueue(7)–(9, 7) size()2(9, 7) enqueue(3)–(9, 7, 3) enqueue(5)–(9, 7, 3, 5) dequeue()9(7, 3, 5) © 2010 Goodrich, Tamassia

38 Queues38 Applications of Queues  Direct applications Waiting lists, bureaucracy Access to shared resources (e.g., printer) Multiprogramming  Indirect applications Auxiliary data structure for algorithms Component of other data structures  Again, queue can be implemented based on Array, ArrayList, Linked List © 2010 Goodrich, Tamassia

39 Queues39 Array-based Queue  Use an array of size N in a circular fashion  Two variables keep track of the front and rear f index of the front element r index immediately past the rear element  Array location r is kept empty Q 012rf normal configuration Q 012fr wrapped-around configuration © 2010 Goodrich, Tamassia Queue is full when the first element is in the first cell or the last element is in the last cell, or the first element is right after the last

40 Data Structures and Algorithms in Java 40 Figure 4-9 Two possible configurations in an array implementation of a queue when the queue is full

41 Queues41 Queue Operations  We use the modulo operator (remainder of division) Algorithm size() return (N  f + r) mod N Algorithm isEmpty() return (f  r) Q 012rf Q 012fr © 2010 Goodrich, Tamassia Java code implementation of Queue based on Array – see Fig 4.10 of the textbook ; on Linked List – Fig.4.11 ( p.153)

42 Queues42 Queue Operations (cont.) Algorithm enqueue(o) if size() = N  1 then throw FullQueueException else Q[r]  o r  (r + 1) mod N  Operation enqueue throws an exception if the array is full  This exception is implementation- dependent Q 012rf Q 012fr © 2010 Goodrich, Tamassia

43 Queues43 Queue Operations (cont.)  Operation dequeue throws an exception if the queue is empty  This exception is specified in the queue ADT Algorithm dequeue() if isEmpty() then throw EmptyQueueException else o  Q[f] f  (f + 1) mod N return o Q 012rf Q 012fr © 2010 Goodrich, Tamassia In both Array and Linked List implementation – enqueueing and dequeueing operations are executed in constant time O(1)

44 Queues44 Queue Interface in Java  Java interface corresponding to our Queue ADT  Requires the definition of class EmptyQueueException  No corresponding built-in Java class public interface Queue { public int size(); public boolean isEmpty(); public E front() throws EmptyQueueException; public void enqueue(E element); public E dequeue() throws EmptyQueueException; } © 2010 Goodrich, Tamassia

45 Queues45 Applications: Round Robin Schedulers  We can implement a round robin scheduler using a queue Q by repeatedly performing the following steps: 1. e = Q.dequeue() 2. Service element e 3. Q.enqueue(e) © 2010 Goodrich, Tamassia Shared Service Queue EnqueueDequeue

46 Data Structures and Algorithms in Java 46 Priority Queues Simple queues are inadequate when first in/first out scheduling has to be overruled using some priority criteria ( e.g. a handicapped person may have priority over others in a post office line) A priority queue can be assigned to enable a particular process, or event, to be executed out of sequence without affecting overall system operation In priority queues, elements are dequeued according to their priority and their current queue position

47 Data Structures and Algorithms in Java 47 Priority Queues (continued) Priority queues can be represented by two variations of linked lists: – in one type : all elements are entry ordered – in another : order is maintained by putting a new element in its proper position according to its priority Total operational times are usually O(n)

48 Data Structures and Algorithms in Java 48 Summary A stack is a linear data structure that can be accessed at only one of its ends for storing and retrieving data. A stack is called an LIFO structure: last in/first out. A queue is a waiting line that grows by adding elements to its end and shrinks by taking elements from its front. A queue is an FIFO structure: first in/first out.

49 Data Structures and Algorithms in Java 49 Summary (continued) In queuing theory, various scenarios are analyzed and models are built that use queues for processing requests or other information in a predetermined sequence (order). A priority queue can be assigned to enable a particular process, or event, to be executed out of sequence without affecting overall system operation.

50 Data Structures and Algorithms in Java 50 Summary (continued) In priority queues, elements are dequeued according to their priority and their current queue position.

51 Programming with Recursion 51 Programming with Recursion© 2010 Goodrich, Tamassia

52 Data Structures and Algorithms in Java 52 Recursive Definitions Recursive definitions are programming concepts that define themselves A recursive definition consists of two parts: –The anchor or ground case, the basic elements that are the building blocks of all other elements of the set are listed –Rules that allow for the construction of new objects out of basic elements or objects that have already been constructed; these rules are applied again and again to generate new objects –Recursive definitions serve two purposes: generating new elements, and testing whether an element belongs to a set.

53 The Recursion Pattern 53  Recursion: when a method calls itself  Classic example: the factorial function: n! = 1· 2· 3· ··· · (n  1)· n  Recursive definition:  Definition above can be easily converted into a Java method: // recursive factorial function public static int recursiveFactorial(int n) { if (n == 0) return 1;// basis case else return n * recursiveFactorial(n- 1);// recursive case }

54 Programming with Recursion 54 Content of a Recursive Method  Base case(s) Values of the input variables for which we perform no recursive calls are called base cases (there should be at least one base case). Every possible chain of recursive calls must eventually reach a base case.  Recursive calls Calls to the current method. Each recursive call should be defined so that it makes progress towards a base case.  Recursion is calling a method that happens to have the same name as the caller. A recursive call is not literally a method calling itself, but rather an instantiation of a method calling another instantiation of the same original. © 2010 Goodrich, Tamassia

55 Using Recursion55 Using Recursion © 2010 Goodrich, Tamassia

56 Using Recursion56 Linear Recursion  Test for base cases Begin by testing for a set of base cases (there should be at least one). Every possible chain of recursive calls must eventually reach a base case, and the handling of each base case should not use recursion.  Recur once Perform a single recursive call This step may have a test that decides which of several possible recursive calls to make, but it should ultimately make just one of these calls Define each possible recursive call so that it makes progress towards a base case. © 2010 Goodrich, Tamassia

57 Using Recursion57 Example of Linear Recursion Algorithm LinearSum(A, n): Input: A integer array A and an integer n = 1, such that A has at least n elements Output: The sum of the first n integers in A if n = 1 then return A[0] else return LinearSum(A, n - 1) + A[n - 1] Example recursion trace: © 2010 Goodrich, Tamassia

58 Using Recursion58 Reversing an Array Algorithm ReverseArray(A, i, j): Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j if i < j then Swap A[i] and A[ j] ReverseArray(A, i + 1, j - 1) return © 2010 Goodrich, Tamassia

59 Using Recursion59 Defining Arguments for Recursion  In creating recursive methods, it is important to define the methods in ways that facilitate recursion.  This sometimes requires we define additional paramaters that are passed to the method.  For example, we defined the array reversal method as ReverseArray(A, i, j), not ReverseArray(A). © 2010 Goodrich, Tamassia

60 Using Recursion60 Computing Powers  The power function, p(x,n)=x n, can be defined recursively:  This leads to an power function that runs in O(n) time (for we make n recursive calls).  We can do better than this, however. © 2010 Goodrich, Tamassia

61 Using Recursion61 Recursive Squaring  We can derive a more efficient linearly recursive algorithm by using repeated squaring:  For example, 2 4 = 2 ( 4 / 2 ) 2 = ( 2 4 / 2 ) 2 = ( 2 2 ) 2 = 4 2 = 16 2 5 = 2 1 +( 4 / 2 ) 2 = 2 ( 2 4 / 2 ) 2 = 2 ( 2 2 ) 2 = 2 ( 4 2 ) = 32 2 6 = 2 ( 6 / 2)2 = ( 2 6 / 2 ) 2 = ( 2 3 ) 2 = 8 2 = 64 2 7 = 2 1 +( 6 / 2 ) 2 = 2 ( 2 6 / 2 ) 2 = 2 ( 2 3 ) 2 = 2 ( 8 2 ) = 128. © 2010 Goodrich, Tamassia

62 Using Recursion62 Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value x n if n = 0then return 1 if n is odd then y = Power(x, (n - 1)/ 2) return x · y ·y else y = Power(x, n/ 2) return y · y © 2010 Goodrich, Tamassia

63 Using Recursion63 Analysis Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value x n if n = 0then return 1 if n is odd then y = Power(x, (n - 1)/ 2) return x · y · y else y = Power(x, n/ 2) return y · y It is important that we use a variable twice here rather than calling the method twice. Each time we make a recursive call we halve the value of n; hence, we make log n recursive calls. That is, this method runs in O(log n) time. © 2010 Goodrich, Tamassia

64 Tail Recursion  All recursions contain a reference to a set or function to be defined  Can be implemented in different ways  Tail recursion is using only one recursive call at the very end of method implementation – when a call is made, there is no statements left to execute in that method © 2010 Goodrich, Tamassia64Stacks

65 65 Tail Recursion Example  Tail recursion is characterized by the use of only one recursive call at the very end of a method implementation void tail (int i) { if (i > 0) { System.out.print (i + ""); tail(i-1); } Tail recursion can be easily replaced by a loop ( see p.179)

66 66 NonTail Recursion Example Example of nontail recursion: void nonTail (int i) { if (i > 0) { nonTail(i-1); System.out.print (i + ""); nonTail(i-1); }

67 Using Recursion67 Tail Recursion  Tail recursion occurs when a linearly recursive method makes its recursive call as its last step.  The array reversal method is an example.  Such methods can be easily converted to non- recursive methods (which saves on some resources).  Example: Algorithm IterativeReverseArray(A, i, j ): Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j while i < j do Swap A[i ] and A[ j ] i = i + 1 j = j - 1 return © 2010 Goodrich, Tamassia

68 Indirect and Nested Recursion  Direct recursion - a method calls itself  Indirect recursion - a method calls itself via a chain of other calls : f() -> f1() -> f2() -> · · · -> fn() -> f()  A function is defined in terms of itself and used as one of its parameters: 0 if n=0 h(n) = { n if n>4 h(2 + h(2n) if n< 4 68

69 Using Recursion69 Binary Recursion  Binary recursion occurs whenever there are two recursive calls for each non-base case.  Example: the DrawTicks method for drawing ticks on an English ruler. © 2010 Goodrich, Tamassia

70 Using Recursion70 A Binary Recursive Method for Drawing Ticks // draw a tick with no label public static void drawOneTick ( int tickLength ) { drawOneTick ( tickLength, - 1 ); } // draw one tick public static void drawOneTick ( int tickLength, int tickLabel ) { for ( int i = 0 ; i < tickLength ; i ++) System. out. print ( "-" ); if ( tickLabel > = 0 ) System. out. print ( " " + tickLabel ); System. out. print ( "\n" ); } public static void drawTicks ( int tickLength ) { // draw ticks of given length if ( tickLength > 0 ) {// stop when length drops to 0 drawTicks ( tickLength- 1 ); // recursively draw left ticks drawOneTick ( tickLength ); // draw center tick drawTicks ( tickLength- 1 ); // recursively draw right ticks } public static void drawRuler ( int nInches, int majorLength ) { // draw ruler drawOneTick ( majorLength, 0 ); // draw tick 0 and its label for ( int i = 1 ; i < = nInches ; i ++) { drawTicks ( majorLength- 1 ); // draw ticks for this inch drawOneTick ( majorLength, i ); // draw tick i and its label } Note the two recursive calls © 2010 Goodrich, Tamassia

71 Using Recursion71 Another Binary Recusive Method  Problem: add all the numbers in an integer array A: Algorithm BinarySum(A, i, n): Input: An array A and integers i and n Output: The sum of the n integers in A starting at index i if n = 1 then return A[i ] return BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2)  Example trace: © 2010 Goodrich, Tamassia

72 Using Recursion72 Computing Fibonacci Numbers  Fibonacci numbers are defined recursively: F 0 = 0 F 1 = 1 F i = F i - 1 + F i - 2 for i > 1.  Recursive algorithm (first attempt): Algorithm BinaryFib( k ) : Input: Nonnegative integer k Output: The kth Fibonacci number F k if k = 1 then return k else return BinaryFib( k - 1 ) + BinaryFib( k - 2 ) © 2010 Goodrich, Tamassia

73 Using Recursion73 Analysis  Let n k be the number of recursive calls by BinaryFib(k) n 0 = 1 n 1 = 1 n 2 = n 1 + n 0 + 1 = 1 + 1 + 1 = 3 n 3 = n 2 + n 1 + 1 = 3 + 1 + 1 = 5 n 4 = n 3 + n 2 + 1 = 5 + 3 + 1 = 9 n 5 = n 4 + n 3 + 1 = 9 + 5 + 1 = 15 n 6 = n 5 + n 4 + 1 = 15 + 9 + 1 = 25 n 7 = n 6 + n 5 + 1 = 25 + 15 + 1 = 41 n 8 = n 7 + n 6 + 1 = 41 + 25 + 1 = 67.  Note that n k at least doubles every other time  That is, n k > 2 k/2. It is exponential! © 2010 Goodrich, Tamassia

74 Using Recursion74 A Better Fibonacci Algorithm  Use linear recursion instead Algorithm LinearFibonacci(k): Input: A nonnegative integer k Output: Pair of Fibonacci numbers (F k, F k  1 ) if k = 1 then return (k, 0) else (i, j) = LinearFibonacci(k  1) return (i +j, i)  LinearFibonacci makes k  1 recursive calls © 2010 Goodrich, Tamassia

75 Using Recursion75 Multiple Recursion  Motivating example: summation puzzles  pot + pan = bib  dog + cat = pig  boy + girl = baby  Multiple recursion: makes potentially many recursive calls not just one or two © 2010 Goodrich, Tamassia

76 Using Recursion76 Algorithm for Multiple Recursion Algorithm PuzzleSolve(k,S,U): Input: Integer k, sequence S, and set U (universe of elements to test) Output: Enumeration of all k-length extensions to S using elements in U without repetitions for all e in U do Remove e from U {e is now being used} Add e to the end of S if k = 1 then Test whether S is a configuration that solves the puzzle if S solves the puzzle then return “Solution found: ” S else PuzzleSolve(k - 1, S,U) Add e back to U {e is now unused} Remove e from the end of S © 2010 Goodrich, Tamassia

77 Data Structures and Algorithms in Java 77 Summary Recursive definitions are programming concepts that define themselves Recursive definitions serve two purposes: –Generating new elements –Testing whether an element belongs to a set Recursive definitions are frequently used to define functions and sequences of numbers

78 Data Structures and Algorithms in Java 78 Summary (continued) Tail recursion is characterized by the use of only one recursive call at the very end of a method implementation. No general rules for when to use it and when to use it. Each particular problem decides. Recursion is usually less efficient than its iterative equivalent. Recursion is often simpler than the iterative solution Every recursive method can be converted into an iterative version Sometimes a recursive version is faster than a nonrecursive implementation.

79 Data Structures and Algorithms in Java Quck Quiz 1.What is a recursion ? 2.Can a recursion do something which iteration cannot ? 3.Can a recursion take less coding than iteration? 4.: Does using recursion usually make your code faster? 5.Does using recursion usually use less memory? 6.Then why use recursion? 79

80 Data Structures and Algorithms in Java Quite a number of good sites on recursion are available on the WEB - below are just some : http://cplus.about.com/od/glossar1/g/recursiondefn.htm http://www.sharpened.net/glossary/definition.php?recursive function and many more. Recursion might look unusual and confusing at first, but it serves well in many cases... 80


Download ppt "Data Structures and Algorithms in Java IT310 Data Structures and Algorithms ( in Java) Seminar 4 Instructor : Vladimir Gubanov, PhD"

Similar presentations


Ads by Google