Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structure course – Part 2 Queue – Stack – Recursion

Similar presentations


Presentation on theme: "Data Structure course – Part 2 Queue – Stack – Recursion"— Presentation transcript:

1 Data Structure course – Part 2 Queue – Stack – Recursion
Dr. Khaled Safi 11/24/2020 Data Structure - AUL University

2 Data Structure - AUL University
Stack A stack is a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle. A user may insert objects into a stack at any time, but may only access or remove the most recently inserted object that remains (at the so-called “top” of the stack). 11/24/2020 Data Structure - AUL University

3 Applications of stacks
Example 1: Internet Web browsers store the addresses of recently visited sites on a stack. Each time a user visits a new site, that site’s address is “pushed” onto the stack of addresses. The browser then allows the user to “pop” back to previously visited sites using the “back” button. Example 2: Text editors usually provide an “undo” mechanism that cancels recent editing operations and reverts to former states of a document. This undo operation can be accomplished by keeping text changes in a stack. 11/24/2020 Data Structure - AUL University

4 The Stack Abstract Data Type
A stack is an abstract data type (ADT) that supports the following two update methods: 11/24/2020 Data Structure - AUL University

5 Data Structure - AUL University
Stack - example 11/24/2020 Data Structure - AUL University

6 A Stack Interface in Java
Java has included a concrete class named java.util.Stack that implements the LIFO semantics of a stack. Methods of our stack ADT and corresponding methods of the class java.util.Stack, with differences highlighted in the right margin. Because of the importance of the stack ADT, Java has included, since its original version, a concrete class named java.util.Stack that implements the LIFO semantics of a stack. However, Java’s Stack class remains only for historic reasons, and its interface is not consistent with most other data structures in the Java library. In fact, the current documentation for the Stack class recommends that it not be used, as LIFO functionality (and more) is provided by a more general data structure known as a double-ended queue (which we describe in Section 6.3) 11/24/2020 Data Structure - AUL University

7 Data Structure - AUL University
Stack interface 11/24/2020 Data Structure - AUL University

8 Data Structure - AUL University
Stack interface 11/24/2020 Data Structure - AUL University

9 A Simple Array-Based Stack Implementation
11/24/2020 Data Structure - AUL University

10 A Simple Array-Based Stack Implementation
11/24/2020 Data Structure - AUL University

11 Analyzing the Array-Based Stack Implementation
+The array implementation of a stack is simple and efficient. - it relies on a fixed-capacity array, which limits the ultimate size of the stack. The Performance: Each method executes a constant number of statements involving arithmetic operations, comparisons, and assignments, or calls to size and isEmpty, which both run in constant time. Thus, in this implementation of the stack ADT, each method runs in constant time, that is, they each run in O(1) time. 11/24/2020 Data Structure - AUL University

12 Sample usage of our ArrayStack class.
11/24/2020 Data Structure - AUL University

13 Implementing a Stack with a Singly Linked List
The linked-list approach has memory usage that is always proportional to the number of actual elements currently in the stack, and without an arbitrary capacity limit. 11/24/2020 Data Structure - AUL University

14 Implementing a Stack with a Singly Linked List
11/24/2020 Data Structure - AUL University

15 Reversing an Array Using a Stack
11/24/2020 Data Structure - AUL University

16 Reversing an Array Using a Stack
11/24/2020 Data Structure - AUL University

17 Matching Parentheses and HTML Tags
we consider arithmetic expressions that may contain various pairs of grouping symbols, such as Parentheses: “(” and “)” Braces: “{” and “}” Brackets: “[” and “] Each opening symbol must match its corresponding closing symbol. 11/24/2020 Data Structure - AUL University

18 An Algorithm for Matching Delimiters
11/24/2020 Data Structure - AUL University

19 Data Structure - AUL University
Queues 11/24/2020 Data Structure - AUL University

20 Data Structure - AUL University
Queue - definition A queue is a collection of objects that are inserted and removed according to the first-in, first-out (FIFO) principle. The elements enter a queue at the back and are removed from the front. Applications: Reservation centers wait-list at a restaurant handle calls to a customer service center networked printer Web server responding to requests. 11/24/2020 Data Structure - AUL University

21 The Queue Abstract Data Type
The queue abstract data type (ADT) supports the following two update methods: enqueue(e): Adds element e to the back of queue. dequeue(): Removes and returns the first element from the queue (or null if the queue is empty). first(): Returns the first element of the queue, without removing it (or null if the queue is empty). size(): Returns the number of elements in the queue. isEmpty(): Returns a Boolean indicating whether the queue is empty. 11/24/2020 Data Structure - AUL University

22 Data Structure - AUL University
Queue interface 11/24/2020 Data Structure - AUL University

23 Data Structure - AUL University
Queue – example 11/24/2020 Data Structure - AUL University

24 java.util.Queue interface
Java provides a type of queue interface, java.util.Queue, which has functionality similar to the traditional queue ADT, 11/24/2020 Data Structure - AUL University

25 Array-Based Queue Implementation
11/24/2020 Data Structure - AUL University

26 Array-Based Queue Implementation
11/24/2020 Data Structure - AUL University

27 The Efficiency of an Array-Based Queue
11/24/2020 Data Structure - AUL University

28 Implementing a Queue with a Singly Linked List
11/24/2020 Data Structure - AUL University

29 Data Structure - AUL University
A Circular Queue A circular queue is an excellent abstraction for applications in which elements are cyclically arranged, such as for multiplayer, turn-based games, or round-robin scheduling of computing processes. we implemented a circularly linked list class that supports all behaviors of a singly linked list, and an additional rotate() method that efficiently moves the first element to the end of the list. We can generalize the Queue interface to define a new CircularQueue interface with such a behavior, as shown in Code Fragment 6.12. 11/24/2020 Data Structure - AUL University

30 Data Structure - AUL University
The Josephus Problem In the children’s game “hot potato,” a group of n children sit in a circle passing an object, called the “potato,” around the circle. The potato begins with a starting child in the circle, and the children continue passing the potato until a leader rings a bell, at which point the child holding the potato must leave the game after handing the potato to the next child in the circle. After the selected child leaves, the other children close up the circle. This process is then continued until there is only one child remaining, who is declared the winner. If the leader always uses the strategy of ringing the bell so that every k th person is removed from the circle, for some fixed value k, then determining the winner for a given list of children is known as the Josephus problem (named after an ancient story with far more severe consequences than in the children’s game) . 11/24/2020 Data Structure - AUL University

31 solving the Josephus problem using a circular queue
11/24/2020 Data Structure - AUL University

32 solving the Josephus problem using a circular queue
11/24/2020 Data Structure - AUL University

33 Data Structure - AUL University
Recursion 11/24/2020 Data Structure - AUL University

34 Recursion - definition
One way to describe repetition within a computer program is the use of loops. An entirely different way to achieve repetition is through a process known as recursion. Recursion is a technique by which a method makes one or more calls to itself during execution. 11/24/2020 Data Structure - AUL University

35 Data Structure - AUL University
Recursion - examples Examples of the use of recursion: The factorial function (commonly denoted as n!) is a classic mathematical function that has a natural recursive definition. An English ruler has a recursive pattern that is a simple example of a fractal structure. Binary search algorithm. It allows us to efficiently locate a desired value in a data set with upwards of billions of entries. The file system for a computer has a recursive structure in which directories can be nested arbitrarily deeply within other directories. Recursive algorithms are widely used to explore and manage these file systems. 11/24/2020 Data Structure - AUL University

36 The Factorial Function
The factorial of a positive integer n, denoted n!, is defined as the product of the integers from 1 to n. For example, 5! = 5 · 4 · 3 · 2 · 1 = 120. This recursive definition can be formalized as : 11/24/2020 Data Structure - AUL University

37 A Recursive Implementation of the Factorial Function
11/24/2020 Data Structure - AUL University

38 A recursion trace for the call factorial(5)
11/24/2020 Data Structure - AUL University

39 Drawing an English Ruler
For each inch, we place a tick with a numeric label. We denote the length of the tick designating a whole inch as the major tick length. Between the marks for whole inches, the ruler contains a series of minor ticks, placed at intervals of 1/2 inch, 1/4 inch, and so on. 11/24/2020 Data Structure - AUL University

40 Drawing an English Ruler
In general, an interval with a central tick length L ≥ 1 is composed of: An interval with a central tick length L – 1 A single tick of length L An interval with a central tick length L - 1 11/24/2020 Data Structure - AUL University

41 Data Structure - AUL University
The main method, drawRuler, manages the construction of the entire ruler. Its arguments specify the total number of inches in the ruler and the major tick length. The utility method, drawLine, draws a single tick with a specified number of dashes (and an optional integer label that is printed to the right of the tick). The interesting work is done by the recursive drawInterval method. This method draws the sequence of minor ticks within some interval, based upon the length of the interval’s central tick. We rely on the intuition shown at the top of this page, and with a base case when L = 0 that draws nothing. For L ≥ 1, the first and last steps are performed by recursively calling drawInterval(L - 1). The middle step is performed by calling method drawLine(L). 11/24/2020 Data Structure - AUL University

42 Data Structure - AUL University
The main method, drawRuler, manages the construction of the entire ruler. Its arguments specify the total number of inches in the ruler and the major tick length. The utility method, drawLine, draws a single tick with a specified number of dashes (and an optional integer label that is printed to the right of the tick). The interesting work is done by the recursive drawInterval method. This method draws the sequence of minor ticks within some interval, based upon the length of the interval’s central tick. We rely on the intuition shown at the top of this page, and with a base case when L = 0 that draws nothing. For L ≥ 1, the first and last steps are performed by recursively calling drawInterval(L - 1). The middle step is performed by calling method drawLine(L). 11/24/2020 Data Structure - AUL University

43 Binary Search - definition
Binary search algorithm is used to efficiently locate a target value within a sorted sequence of n elements stored in an array. Consider an arbitrary element of the sequence with value v, we can be sure that all elements prior to that in the sequence have values <= to v, and that all elements after that element in the sequence have values >= to v. 11/24/2020 Data Structure - AUL University

44 Binary Search - definition
The algorithm maintains two parameters, low and high, such that all the candidate elements have index at least low and at most high. Initially, low = 0 and high = n - 1. We then compare the target value to the median candidate, that is, the element with index mid = ⌊(low + high)/2⌋. We consider three cases: If the target equals the median candidate, then we have found the item we are looking for, and the search terminates successfully. If the target is less than the median candidate, then we recur on the first half of the sequence, that is, on the interval of indices from low to mid - 1. If the target is greater than the median candidate, then we recur on the second half of the sequence, that is, on the interval of indices from mid + 1 to high. 11/24/2020 Data Structure - AUL University

45 Binary Search - implementation
11/24/2020 Data Structure - AUL University

46 Binary Search - Example
Example of a binary search for target value 22 on a sorted array with 16 elements. 11/24/2020 Data Structure - AUL University

47 Data Structure - AUL University
File Systems 11/24/2020 Data Structure - AUL University

48 Analyzing Recursive Algorithms
we may rely on the intuition afforded by a recursion trace in recognizing how many recursive activations occur, and how the parameterization of each activation can be used to estimate the number of primitive operations that occur within the body of that activation. What is the running time of a recursive algorithm? 11/24/2020 Data Structure - AUL University

49 Data Structure - AUL University
Computing Factorials To compute factorial(n), we see that there are a total of n+1 activations, as the parameter decreases from n in the first call, to n-1 in the second call, and so on, until reaching the base case with parameter 0. It is also clear, that each individual activation of factorial executes a constant number of operations. Therefore, we conclude that the overall number of operations for computing factorial(n) is O(n), as there are n+1 activations, each of which accounts for O(1) operations. 11/24/2020 Data Structure - AUL University

50 Drawing an English Ruler
We know that a call to drawInterval(c) for c > 0 spawns two calls to drawInterval(c - 1) and a single call to drawLine. Proposition: For c ≥ 0, a call to drawInterval(c) results in precisely 2c – 1 lines of output. Justification: by induction An application of drawInterval(0) generates no output, and that = 1-1 = 0. More generally, the number of lines printed by drawInterval(c) is one more than twice the number generated by a call to drawInterval(c-1), as one center line is printed between two such recursive calls. By induction, we have that the number of lines is thus ·(2c-1 - 1) = 1+2c - 2 = 2c - 1. 11/24/2020 Data Structure - AUL University

51 Performing a Binary Search
The running time is proportional to the number of recursive calls performed. We will show that at most ⌊logn⌋ + 1 recursive calls are made during a binary search of a sequence having n elements. Proposition: The binary search algorithm runs in O(logn) time for a sorted array with n elements. 11/24/2020 Data Structure - AUL University

52 Data Structure - AUL University
11/24/2020 Data Structure - AUL University

53 Further Examples of Recursion
We organize our presentation by considering the maximum number of recursive calls that may be started from within the body of a single activation. If a recursive call starts at most one other, we call this a linear recursion. If a recursive call may start two others, we call this a binary recursion. If a recursive call may start three or more others, this is multiple recursion. 11/24/2020 Data Structure - AUL University

54 Data Structure - AUL University
Linear Recursion If a recursive method is designed so that each invocation of the body makes at most one new recursive call, this is know as linear recursion. Examples: Factorial method Binary search method Note that the linear recursion terminology reflects the structure of the recursion trace, not the asymptotic analysis of the running time; for example, we have seen that binary search runs in O(logn) time. 11/24/2020 Data Structure - AUL University

55 Summing the Elements of an Array Recursively
We can solve this summation problem using linear recursion. 11/24/2020 Data Structure - AUL University

56 Summing the Elements of an Array Recursively
11/24/2020 Data Structure - AUL University

57 Reversing a Sequence with Recursion
11/24/2020 Data Structure - AUL University

58 Data Structure - AUL University
Binary Recursion When a method makes two recursive calls, we say that it uses binary recursion. We have already seen an example of binary recursion when drawing the English ruler. Example: problem of summing the n integers of an array: 11/24/2020 Data Structure - AUL University

59 Data Structure - AUL University
Selection sort and Insertion sort (another presentation) 11/24/2020 Data Structure - AUL University

60 Data Structure - AUL University
Selection algorithms The problem of selecting the kth smallest element from an unsorted collection of n comparable elements. This is known as the selection problem. Of course, we can solve this problem by sorting the collection and then indexing into the sorted sequence at index k - 1 . Using the best comparison-based sorting algorithms, this approach would take O(nlogn) time. Thus, a natural question to ask is whether we can achieve an O(n) running time for all values of k (including the interesting case of finding the median, where k = ⌊n/2⌋) 11/24/2020 Data Structure - AUL University

61 Data Structure - AUL University
Prune-and-Search We can indeed solve the selection problem in O(n) time for any value of k . the technique used to achieve this result involves an interesting design pattern is known as prune-and-search. In applying this design pattern, we solve a given problem that is defined on a collection of n objects by pruning away a fraction of the n objects and recursively solving the smaller problem. The binary search method is an example of the prune-and- search design pattern 11/24/2020 Data Structure - AUL University

62 Randomized Quick-Select
Suppose we are given an unsorted sequence S of n elements with an integer k ∈ [1,n]. At a high level, the quick-select algorithm for finding the kth smallest element in S is similar to the randomized quick-sort algorithm. We pick a “pivot” element from S at random and use this to subdivide S into three subsequences L, E, and G, storing the elements of S less than, equal to, and greater than the pivot, respectively. In the prune step, we determine which of these subsets contains the desired element, based on the value of k and the sizes of those subsets 11/24/2020 Data Structure - AUL University

63 Randomized Quick-Select
11/24/2020 Data Structure - AUL University

64 Data Structure - AUL University
11/24/2020 Data Structure - AUL University


Download ppt "Data Structure course – Part 2 Queue – Stack – Recursion"

Similar presentations


Ads by Google