Abstract Data Types. Stack ADT
|
|
- Phebe Fox
- 5 years ago
- Views:
Transcription
1 Abstract Data Types Data abstraction consepts have been introduced in previous courses, for example, in Chapter 7 of [Deitel]. The Abstract Data Type makes data abstraction more formal. In essence, an abstract data type (ADT) consists of the following: A collection of data A set of operations on the data or subsets of the data A set of axioms, or rules of behavior governing the interaction of operations The ADT concept is similar and related to the classical systems of mathematics, where an entity (such as a number system, group, or field) is defined in terms of operations and axioms. The ADT is also closely related to set theory, and in fact could be considered a variant of set theory. The concepts of vector, list, and deque, introduced in earlier chapters, could also be described as ADTs. Before proceeding to our primary examples of ADTs, stack and queue, let's clarify the distinction between a data structure and an ADT. A data structure is an implementation. For example, Vector, List, and Deque are data structures. An abstract data type is a system described in terms of its behavior, without regard to its implementation. The data structures Vector, List, and Deque implement the ADTs vector, list, and deque, respectively. We return to the discussion of these ADTs later in this chapter. Within the context of C++ (or most other object-oriented languages such as Java and Smalltalk), an abstract data type can be defined as a class public interface with the ADT axioms stated as behavior requirements. A data structure in this context is a fully implemented class, whether or not explicit requirements have been placed on its behavior -- it is what it is. Of course, we often do place requirements on behavior prior to implementation, as we did for Vector, List, and Deque. The C++ language standard, in fact, places behavior and performance requirements on all of the classes in the STL. Both of these examples (our class, and the C++ STL) have thus integrated ADT concepts into the software development process: start with an ADT and then design a data structure that implements it. Conversely, any proper class can in principle be analyzed, axiomatized, and used to define a corresponding ADT, which the class implements. In this chapter we will concentrate on the stack and queue ADTs: definition, properties, uses, and implementations. The stack and queue are arguably the most important, and certainly the most often encountered, ADTs in computer science. A final comment is critically important: without the third component, the definition of ADT is vacuous of significance. For example, note that the choices of operation names are inherently meaningless, and without axioms they have no constraints on their behavior. When you see the definitions of statck and queue, a little analysis should convince you that it is only the axioms that give meaning to, and distinguish between, the two concepts. Stack ADT The stack ADT operates on a collection comprised of elements of any proper type T and, like most ADTs, inserts, removes, and manipulates data items from the collection. The stack operations are traditionally named as follows: void push (T t) void pop () T top () bool empty () unsigned int size () constructor and destructor 1/11
2 The stack ADT has the following axioms: 1. S.size(), S.empty(), S.push(t) are always defined 2. S.pop() and S.top() are defined iff S.empty() is false 3. S.empty(), S.size(), S.top() do not change S 4. S.empty() is true iff 0 = S.size() 5. S.push(t) followed by S.pop() leaves S unchanged 6. after S.push(t), S.top() returns t 7. S.push(t) increases S.size() by 1 8. S.pop() decreases S.size() by 1 These axioms can be used to prove, among other things, that the stack is unique up to isomorphism: Given any two stacks on the same data type, there is a one-to-one correspondence between their elements that respects the stack operations. Another way to state this fact is that the only possible difference between two stacks on the same data type is changes in terminology; the essential functionalities are identical. Stack Model -- LIFO The stack models the behavior called "LIFO", which stands for "last-in, first-out", the behavior described by axioms 5 and 6. The element most recently pushed onto the stack is the one that is at the top of the stack and is the element that is removed by the next pop operation. The slide illustrates a stack starting empty (as all stacks begin their existence) and follows the stack through three push operations and one pop operation. Derivable Behaviors (Theorems) For the following theorems, assume that S is a stack of elements of type T. Theorem. If (n = S.size()) is followed by k push operations then n + k = S.size(). Proof. Note that stack axiom 7 states the theorem in the case k = 1. Suppose that the theorem is true for the case k. Then, if we push k + 1 elements onto S, axiom 7 again states that the size is increased by one from the size after k pushes, that is, from (n + k) to (n + k) + 1 = n + k + 1, completing the induction step. Therefore the theorem is proved, by the principle of mathematical induction. Corollary: The size of a stack is non-negative. Proof. If the size of S is n < 0, then we obtain a stack of size 0 by pushing -n elements onto S. But S is not empty by axiom 5. This contradicts axiom 4. Theorem. If (n = S.size()) is followed by k pop operations then n - k = S.size(). Proof. (Left as an exercise for the student.) Corollary. k <= n; that is, a stack of size n can be popped at most n times without intervening push operations. Proof. The size of a stack cannot be negative. Theorem. The last element of S pushed onto S is the top of S. Proof. Actually, this reiterates axiom /11
3 Theorem. S.pop() removes the last element of S pushed onto S. Proof. By axiom 5, S.pop() does not remove anything that was on the stack prior to the last push operation. The only other possibility is that it removes the item added by the preceding push. Theorem. Any two stacks of type T are isomorphic. This last result is beyond the scope of this course. The proof is not difficult, but it would require the development of considerable apparatus, such as defining isomorphism, and the end the result would be is difficult to appreciate, beyond the intuitive level, without dwelling longer on the various implications of isomorphism. Therefore we will skip the proof. Another point that should be addressed, if we were starting a course in the theory of ADTs, is the independence of the axioms. The axioms listed for ADT stack were assembled to make it easy to prove theorems and to accept, at least intuitively, that they characterize stack as a type. It is possible that one of these axioms could be derived from the others, however. Uses of ADT Stack Stacks (and queues) are ubiquitous in computing. Stacks, in particular, serve as a basic framework to manage general computational systems as well as in supports of specific algorithms. All modern computers have both hardware and software stacks, the former to manage calculations and the latter to manage runtime of languages such as C++. We now discuss five of the archetypical applications of the stack ADT. A widely used search process, depth first search (DFS), is implemented using a stack. The idea behind DFS, using the context of solving a maze, is to continue down paths until the way is blocked, then backtrack to the last unattempted branch path, and continue. The process ends when a goal is reached or there are no unsearched paths. A stack is used to keep track of the state of the search, pushing steps onto the stack as they are taken and popping them off during backtracking. All modern general-purpose computers have a hardware-supported stack for evaluating postfix expressions. To use the postfix evaluation stack effectively, computations must be converted from infix to postfix notation. This translation is part of modern compilers and interpreters and uses a software stack. C++ uses a runtime system that manages the memory requirements of an executing program. A stack, called the runtime stack, is used to organize the function calls in the program. When a function is called, an activation record is pushed onto the runtime stack. When the function returns, its activation record is popped. Among other things, this system makes it straightforward for a function to call itself -- just push another activation record onto the runtime stack. Stack-based runtime systems thus facilitate the use of recursion in programs. Queue ADT The queue ADT operates on a collection comprised of elements of any proper type T and, like most ADTs, inserts, removes, and manipulates data items from the collection. We will break from tradition and use the following names for queue operations: void push (T t) void pop () T front () bool empty () unsigned int size () 3/11
4 constructor and destructor The queue ADT has the following axioms: 1. Q.size(), Q.empty(), Q.push(t) are always defined 2. Q.pop() and Q.front() are defined iff Q.empty() is false 3. Q.empty(), Q.size(), Q.front() do not change Q 4. Q.empty() is true iff 0 = Q.size() 5. Suppose n = Q.size() and the next element pushed onto Q is t; then, after n elements have been popped from Q, t = Q.front() 6. Q.push(t) increases Q.size() by 1 7. Q.pop() decreases Q.size() by 1 8. If t = Q.front() then Q.pop() removes t from Q These axioms can be used to prove, among other things, that the queue is unique up to isomorphism: Given any two queues on the same data type, there is a one-to-one correspondence between their elements that respects the queue operations. Another way to state this fact is that the only possible difference between two queues on the same data type is changes in terminology; the essential functionalities are identical. Queue Model -- FIFO The queue models the behavior called "FIFO", which stands for "first-in, first-out", the behavior described by axiom 5. The element that has been on the queue the longest is the one that is at front of the queue and is the element that is removed by the next pop operation. The slide illustrates a queue starting empty (as all queues begin their existence) and follows the queue through four push and three pop operations. Derivable Behaviors (Theorems) For the following theorems, assume that Q is a queue of elements of type T. Theorem. If (n = Q.size()) is followed by k push operations then n + k = Q.size(). Proof. Apply mathematical induction using axiom 6. Theorem. If (n = Q.size()) is followed by k pop operations then n - k = Q.size(). Proof. Apply mathematical induction using axiom 7. Corollary. k <= n; that is, a queue of size n can be popped at most n times without intervening push operations. Theorem. The first element pushed onto Q (of those still in Q) is the front of Q. Proof. Axiom 5 states that the youngest element on the queue requires size pop operations to be removed. It follows that all of the older elements are popped before the youngest. (The eskimo mafia rule: the older you are, the sooner you are popped.) Theorem. Q.pop() removes the front element of Q. Theorem. Any two queues of type T are isomorphic. Proof. (Beyond our scope.) 4/11
5 Uses of ADT Queue Queues (and stacks) are ubiquitous in computing. Queues, in particular, support general computing as buffers (essential for almost any conceivable I/O), are central to algorithms such as breadth first search, and are a key concept in many simulations. Just as ADT stack is embedded in the hardware of modern CPUs to support evaluation of expressions, ADT queue, in the form of buffers, is an essential component to virtually all computerbased communication. Buffers facilitate transfer of data, making it unnecessary to synchronize send with recieve, without which every computation would be hopelessly I/O bound. ADT queue is a model of actual queues of people, jobs, and processes as well. Thus queues are a natural component of many simulation models of real processes, from fast food restaurents to computer operating systems. The BFS algorithm is detailed later in this chapter. Depth-First Search (DFS) -- Backtracking The DFS algorithm applies to any graph-like structure, including directed graphs, undirected graphs, trees, and mazes. The basic idea of DFS is "go deep" whenever possible but backtrack when necessary. GoDeep: If there is an unvisited neighbor (a location adjacent to the current location), go there. BackTrack: Retreat along the path to the most recently encountered location with an unvisited neighbor. The DFS algorithm initializes at the start location and repeats "if (possible) GoDeep else BackTrack" until there are no moves left or until the goal is encountered. Our version of DFS is single-goal oriented. Another version is oriented toward visiting every location, and consists of applying the goal-oriented version repeatedly at every unvisited location until all locations have been visited. See Chapter VI of [Cormen]. DFS -- Backtracking (cont.) A stack of locations is a convenient way to organize DFS. This slide depicts a setup for DFS consisting of a graph, a starting vertex, a goal vertex, and a stack. The contents of the stack during the run of the DFS algorithm are also shown. The following is a pseudo-code version of the stackbased DFS algorithm. Assumptions: G is a graph with vertices start and goal. Body: DFS stack<locations> S; mark start visited; S.push(start); While (S is not empty) 5/11
6 t = S.top(); if (t == goal) Success(S); return; if (t has unvisited neighbors) choose a next unvisited neighbor n; mark n visited; S.push(n); else BackTrack(S); Failure(S); BackTrack(S) while (!S.empty() && S.top() has no unvisited neighbors) S.pop(); Success(S) cout << "Path from " << goal << " to " << start << ": "; while (!S.empty()) output (S.top()); S.pop(); Failure(S) cout << "No path from " << start << " to " << goal; while (!S.empty()) S.pop(); Outcome. If there is a path in G from start to goal, DFS finds one such path. Proof. We use mathematical induction on the number n of vertices in G. Base case (n = 1). If G has only one vertex, it must be both start and goal. There is a path, and that path is discovered by the algorithm by looking at S.top() immediately after initialization with S.push(start). Induction step. Assume that the result is true for any graph of size less than n, and consider our given graph G of size n. Suppose that there is a path in G from start to goal. Let H be the subgraph of G obtained by removing goal and the edges incident to goal. Note that H contains all vertices of G except goal, and all but the last edge of the known path from start to goal. The induction hypothesis implies that DFS finds a path in H from start to the end of this truncated path, a neighbor of goal. This neighbor of goal is thus at the top of S at the point of successfully finding this path. 6/11
7 The algorithm runs in exactly the same way on G, either finding a path involving a different neighbor of goal or arriving at the state with a neighbor of goal at the top of S. Since goal is an unvisited neighbor of the top of S, the algorithm pushes goal onto S before any more backtracking can occur. The next cycle of the loop discovers goal at the top of S. It remains to show that the contents of the stack form a path from start to goal. Note that each time a vertex is pushed onto S, it is a neighbor of the top of S. Thus the contents of S do form a path from the bottom (start) to the top (goal). Breadth-First Search (BFS) If DFS is "go deep" then BFS is "go wide". We could compare the two by solving mazes. DFS solves a maze as a single person might: search as far down a path as possible, and when blocked, retreat to the first place from which the search can continue. Stop when the goal is found or the possibilities are exhausted. BFS, on the other hand, solves a maze using a committee. The committee starts out together. Every time there is a fork in the maze, the committee breaks into subcommittees and sends a subcommittee down each path of the fork. The first subcommittee arriving at the goal blows a whistle, or else the process continues until all possibilities have been exhausted. Note that the committee arriving at the goal first has found the shortest path solving the maze, and the length of this path is the distance from the start to the goal. BFS (cont.) A queue of locations is a convenient way to organize BFS. This slide depicts a setup for BFS consisting of a graph, a starting vertex, a goal vertex, and a queue. The contents of the queue during the run of the BFS algorithm are also shown. The following is a pseudo-code version of the queue-based BFS algorithm. Assumptions: G is a graph with vertices start and goal. Body: BFS queue<locations> Q; mark start visited; Q.push(start); While (Q is not empty) t = Q.front(); for each unvisited neighbor n of t Q.push(n); if (n == goal) Success(S); return; Q.pop(); Failure(Q); 7/11
8 Success() // must build solution using backtrack pointers Outcome. If there is a path in G from start to goal, BFS finds a shortest such path. This version of BFS, like DFS above, is goal-oriented. A broader version that searches an entire graph is discussed very thoroughly in Chapter VI of [Cormen], including proofs of correctness and runtime analysis. The algorithm above would need some embellishment to keep track of data, depending on the desired outome. We postpone further analysis of BFS and DFS to COP Evaluating Postfix Expressions -- Algorithm The process of evaluating expressions is an important part of most computer programs, and typically breaks into two distinct steps: 1. Translation of infix expression to postfix expression 2. Evaluation of postfix expression The first step is usually accomplished in software, either compiler or interpreter. The second step is usually accomplished with significant hardware support. However, both of these steps are facilitated with the stack ADT. We discuss the evaluation algorithm here, and discuss the translation algorithm after introducing our stack implementation later in this chapter. Both translation and evaluation use the concept of token. A token is an atomic symbol in a computer program or computation. For example, the code fragment int num1, num2; cin >> num1; num2 = num1 + 5; my_function(num2); contains the following stream of tokens (written vertically for clarity): int num1, num2 ; cin >> num1 ; num2 = num1 + 5 ; my_function ( num2 ) ; and for the expression 8/11
9 z = 25 + x*(y - 5) the token stream is z = 25 + x * ( y - 5 ) The postfix evaluation algorithm is described in the following pseudo code: Evaluate(postfix expression) uses stack of tokens; while (expression is not empty) t = next token; if (t is operand) push t onto stack else // t is an operator pop operands for t off stack; evaluate t on these operands; push result onto stack; // at this point, there should be exactly one operand on the stack return top of stack; Evaluating Postfix Expressions -- Example The slide illustrates the evaluation algorithm applied to the expression * which is the postfix translate of the prefix expression 1 + (2 + 3) * The stack operations and the stack state after each operation are shown. Runtime Stack and Recursion Most modern programming languages use a runtime environment that includes a runtime stack of function activation records and a runtime heap where dynamic allocation and de-allocation of memory is managed. (The latter may be automated by a garbage collection system -- a slow, but programmer-friendly, memory management system.) As a C++ executable is loaded, a set of contiguous memory addresses is assigned to it by the 9/11
10 operating system. This interval [bottom, top] of addresses is the address space assigned to the running program. The address space is organized as follows: [static stack -->... <-- heap] where '[' denotes the bottom of the address space and ']' denotes the top. The static area is a fixed size and contains such things as the executable code for all program functions, locations for global variables and constants, and a symbol table in which identifiers are matched with addresses (relative to '['). The stack and heap are dynamic in size. The stack grows upward in address space and the heap grows downward. If the stack and heap collide, then memory allocated to the program has been used up and the program crashes. (With virtual memory addressing and no limits set for the program, such a crash is "virtually" impossible. But without virtual memory, or with memory limits set, this kind of crash can and often does occur.) The stack is the mechanism by which the runtime state of the program is maintained. The stack element type is AR or activation record. An activation record contains all essential information about a function, including: function name, location of function code, function parameters, function return value, and location where control is returned (location of function call). In C/C++, execution begins by pushing the activation record of main() onto the newly created stack. For every function call, a new activation record is pushed onto the runtime stack. Thus the top of the stack is always a record of the currently running function. Whenever a function returns, its activation record is popped off the stack and control is returned to the calling process (whose activation record is now at the top of the stack). Execution ends when main() returns and the stack is popped to the empty state. The runtime stack requires no restriction on which function activation records may be used at any given point in an executing program. In particular, there is no reason not to permit the same function to be activated twice or more in succession. This innocuous observation is the basis for languages such as C++ to implement recursion. In the context of programming, recursion is the phenomenon of a function calling itself as in the implementation int fib (int n) if (n <= 0) return 0; if (n == 1) return 1; return fib(n - 2) + fib(n -1); or a finite sequence of functions each calling the next until the last calls the first, as in the implementation int F (int n) if (n <= 0) return 1; return G(n); int G (int n) return n * F(n - 1); The number of functions involved in the circular chain of calls is the order of the recursion. (The first example above is order one recursion and the second is order two recursion.) Recursion and 10/11
11 recursive programming are important topics to which we return in a later chapter. 11/11
Abstract Data Types. Stack ADT. Stack Model LIFO
Abstract Data Types Data abstraction consepts have been introduced in previous courses, for example, in Chapter 7 of [Deitel]. The Abstract Data Type makes data abstraction more formal. In essence, an
More informationTopics. Trees Vojislav Kecman. Which graphs are trees? Terminology. Terminology Trees as Models Some Tree Theorems Applications of Trees CMSC 302
Topics VCU, Department of Computer Science CMSC 302 Trees Vojislav Kecman Terminology Trees as Models Some Tree Theorems Applications of Trees Binary Search Tree Decision Tree Tree Traversal Spanning Trees
More information12 Abstract Data Types
12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define
More informationData Structures and Algorithms
Data Structures and Algorithms Alice E. Fischer Lecture 6: Stacks 2018 Alice E. Fischer Data Structures L5, Stacks... 1/29 Lecture 6: Stacks 2018 1 / 29 Outline 1 Stacks C++ Template Class Functions 2
More informationCSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills
CSCI 136 Data Structures & Advanced Programming Lecture 14 Fall 2018 Instructor: Bills Announcements Mid-Term Review Session Monday (10/15), 7:00-8:00 pm in TPL 203 No prepared remarks, so bring questions!
More informationLecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this
Lecture Notes Array Review An array in C++ is a contiguous block of memory. Since a char is 1 byte, then an array of 5 chars is 5 bytes. For example, if you execute the following C++ code you will allocate
More informationChapter 14. Graphs Pearson Addison-Wesley. All rights reserved 14 A-1
Chapter 14 Graphs 2011 Pearson Addison-Wesley. All rights reserved 14 A-1 Terminology G = {V, E} A graph G consists of two sets A set V of vertices, or nodes A set E of edges A subgraph Consists of a subset
More informationCS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory
CS490: Problem Solving in Computer Science Lecture 6: Introductory Graph Theory Dustin Tseng Mike Li Wednesday January 16, 2006 Dustin Tseng Mike Li: CS490: Problem Solving in Computer Science, Lecture
More informationMultidimensional Arrays & Graphs. CMSC 420: Lecture 3
Multidimensional Arrays & Graphs CMSC 420: Lecture 3 Mini-Review Abstract Data Types: List Stack Queue Deque Dictionary Set Implementations: Linked Lists Circularly linked lists Doubly linked lists XOR
More informationData Structure. IBPS SO (IT- Officer) Exam 2017
Data Structure IBPS SO (IT- Officer) Exam 2017 Data Structure: In computer science, a data structure is a way of storing and organizing data in a computer s memory so that it can be used efficiently. Data
More informationLists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50
Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures and Programming Spring 2016 1 / 50 Abstract Data Types (ADT) Data type a set of objects + a set of operations Example: integer set
More informationAbstract Data Types 1
Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Abstract Data Types (ADTs) ADT is a set of objects together with a set of operations. Abstract in that implementation of operations
More informationTrees. Arash Rafiey. 20 October, 2015
20 October, 2015 Definition Let G = (V, E) be a loop-free undirected graph. G is called a tree if G is connected and contains no cycle. Definition Let G = (V, E) be a loop-free undirected graph. G is called
More informationEC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3
UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between
More informationProblem with Scanning an Infix Expression
Operator Notation Consider the infix expression (X Y) + (W U), with parentheses added to make the evaluation order perfectly obvious. This is an arithmetic expression written in standard form, called infix
More informationAbstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University
Abstract Data Types CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues
More informationAnnouncements. HW3 is graded. Average is 81%
CSC263 Week 9 Announcements HW3 is graded. Average is 81% Announcements Problem Set 4 is due this Tuesday! Due Tuesday (Nov 17) Recap The Graph ADT definition and data structures BFS gives us single-source
More informationMarch 13/2003 Jayakanth Srinivasan,
Statement Effort MergeSort(A, lower_bound, upper_bound) begin T(n) if (lower_bound < upper_bound) Θ(1) mid = (lower_bound + upper_bound)/ 2 Θ(1) MergeSort(A, lower_bound, mid) T(n/2) MergeSort(A, mid+1,
More informationAlgorithm Design and Analysis
Algorithm Design and Analysis LECTURE 4 Graphs Definitions Traversals Adam Smith 9/8/10 Exercise How can you simulate an array with two unbounded stacks and a small amount of memory? (Hint: think of a
More informationHeap, Variables, References, and Garbage. CS152. Chris Pollett. Oct. 13, 2008.
Heap, Variables, References, and Garbage. CS152. Chris Pollett. Oct. 13, 2008. Outline. Dynamic Allocation. Variables and Constants. Aliases and Problems. Garbage. Introduction. On Wednesday, we were talking
More informationTrees. 3. (Minimally Connected) G is connected and deleting any of its edges gives rise to a disconnected graph.
Trees 1 Introduction Trees are very special kind of (undirected) graphs. Formally speaking, a tree is a connected graph that is acyclic. 1 This definition has some drawbacks: given a graph it is not trivial
More information1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.
1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered
More informationINSTITUTE OF AERONAUTICAL ENGINEERING
INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech
More informationScribes: Romil Verma, Juliana Cook (2015), Virginia Williams, Date: May 1, 2017 and Seth Hildick-Smith (2016), G. Valiant (2017), M.
Lecture 9 Graphs Scribes: Romil Verma, Juliana Cook (2015), Virginia Williams, Date: May 1, 2017 and Seth Hildick-Smith (2016), G. Valiant (2017), M. Wootters (2017) 1 Graphs A graph is a set of vertices
More informationGraph Algorithms. Chapter 22. CPTR 430 Algorithms Graph Algorithms 1
Graph Algorithms Chapter 22 CPTR 430 Algorithms Graph Algorithms Why Study Graph Algorithms? Mathematical graphs seem to be relatively specialized and abstract Why spend so much time and effort on algorithms
More informationDATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305
Q.1 If h is any hashing function and is used to hash n keys in to a table of size m, where n
More informationSTACKS AND QUEUES. Problem Solving with Computers-II
STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()
More informationUndirected Graphs. V = { 1, 2, 3, 4, 5, 6, 7, 8 } E = { 1-2, 1-3, 2-3, 2-4, 2-5, 3-5, 3-7, 3-8, 4-5, 5-6 } n = 8 m = 11
Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. V = {
More informationAlgorithms: Lecture 10. Chalmers University of Technology
Algorithms: Lecture 10 Chalmers University of Technology Today s Topics Basic Definitions Path, Cycle, Tree, Connectivity, etc. Graph Traversal Depth First Search Breadth First Search Testing Bipartatiness
More informationW4231: Analysis of Algorithms
W4231: Analysis of Algorithms 10/21/1999 Definitions for graphs Breadth First Search and Depth First Search Topological Sort. Graphs AgraphG is given by a set of vertices V and a set of edges E. Normally
More informationChapter 9 STACK, QUEUE
Chapter 9 STACK, QUEUE 1 LIFO: Last In, First Out. Stacks Restricted form of list: Insert and remove only at front of list. Notation: Insert: PUSH Remove: POP The accessible element is called TOP. Stack
More informationAbstract Data Types 1
Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Primitive vs. Abstract Data Types Primitive DT: programmer ADT: programmer Interface (API) data Implementation (methods) Data
More informationAn Introduction to Trees
An Introduction to Trees Alice E. Fischer Spring 2017 Alice E. Fischer An Introduction to Trees... 1/34 Spring 2017 1 / 34 Outline 1 Trees the Abstraction Definitions 2 Expression Trees 3 Binary Search
More information-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.
Topic 15 Implementing and Using "stack n. The set of things a person has to do in the future. "I haven't done it yet because every time I pop my stack something new gets pushed." If you are interrupted
More informationABSTRACT DATA TYPES (ADTS) COMP1927 Computing 2 16x1 Sedgewick Chapter 4
ABSTRACT DATA TYPES (ADTS) COMP1927 Computing 2 16x1 Sedgewick Chapter 4 ABSTRACTION To understand a system, it should be enough to understand what its components do without knowing how Watching a television
More informationStack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5
What is Stack? Stack 1. Stack is LIFO Structure [ Last in First Out ] 2. Stack is Ordered List of Elements of Same Type. 3. Stack is Linear List 4. In Stack all Operations such as Insertion and Deletion
More informationCS 270 Algorithms. Oliver Kullmann. Binary search. Lists. Background: Pointers. Trees. Implementing rooted trees. Tutorial
Week 7 General remarks Arrays, lists, pointers and 1 2 3 We conclude elementary data structures by discussing and implementing arrays, lists, and trees. Background information on pointers is provided (for
More informationCPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues
CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues Alan J. Hu (Slides borrowed from Steve Wolfman) Be sure to check course webpage! http://www.ugrad.cs.ubc.ca/~cs221 1 Lab 1 is available.
More informationCS302 Data Structures using C++
CS302 Data Structures using C++ Study Guide for the Final Exam Fall 2018 Revision 1.1 This document serves to help you prepare towards the final exam for the Fall 2018 semester. 1. What topics are to be
More informationLecture 24 Search in Graphs
Lecture 24 Search in Graphs 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, André Platzer, Rob Simmons, Penny Anderson, Iliano Cervesato In this lecture, we will discuss the question
More informationArrays and Linked Lists
Arrays and Linked Lists Abstract Data Types Stacks Queues Priority Queues and Deques John Edgar 2 And Stacks Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation Where every
More informationCMPSCI 250: Introduction to Computation. Lecture #14: Induction and Recursion (Still More Induction) David Mix Barrington 14 March 2013
CMPSCI 250: Introduction to Computation Lecture #14: Induction and Recursion (Still More Induction) David Mix Barrington 14 March 2013 Induction and Recursion Three Rules for Recursive Algorithms Proving
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationMatching Theory. Figure 1: Is this graph bipartite?
Matching Theory 1 Introduction A matching M of a graph is a subset of E such that no two edges in M share a vertex; edges which have this property are called independent edges. A matching M is said to
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationIV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard
IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two
More informationGraph Algorithms. Imran Rashid. Jan 16, University of Washington
Graph Algorithms Imran Rashid University of Washington Jan 16, 2008 1 / 26 Lecture Outline 1 BFS Bipartite Graphs 2 DAGs & Topological Ordering 3 DFS 2 / 26 Lecture Outline 1 BFS Bipartite Graphs 2 DAGs
More informationDepth-First Search Depth-first search (DFS) is another way to traverse the graph.
Depth-First Search Depth-first search (DFS) is another way to traverse the graph. Motivating example: In a video game, you are searching for a path from a point in a maze to the exit. The maze can be modeled
More informationCS510 \ Lecture Ariel Stolerman
CS510 \ Lecture02 2012-10-03 1 Ariel Stolerman Midterm Evan will email about that after the lecture, at least 2 lectures from now. The exam will be given in a regular PDF (not an online form). We will
More informationDEEPIKA KAMBOJ UNIT 2. What is Stack?
What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you
More informationADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )
ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a
More informationCSE 417: Algorithms and Computational Complexity. 3.1 Basic Definitions and Applications. Goals. Chapter 3. Winter 2012 Graphs and Graph Algorithms
Chapter 3 CSE 417: Algorithms and Computational Complexity Graphs Reading: 3.1-3.6 Winter 2012 Graphs and Graph Algorithms Slides by Kevin Wayne. Copyright 2005 Pearson-Addison Wesley. All rights reserved.
More informationDiscrete Mathematics and Probability Theory Fall 2013 Vazirani Note 7
CS 70 Discrete Mathematics and Probability Theory Fall 2013 Vazirani Note 7 An Introduction to Graphs A few centuries ago, residents of the city of Königsberg, Prussia were interested in a certain problem.
More informationDATA STRUCTURES AND ALGORITHMS
DATA STRUCTURES AND ALGORITHMS For COMPUTER SCIENCE DATA STRUCTURES &. ALGORITHMS SYLLABUS Programming and Data Structures: Programming in C. Recursion. Arrays, stacks, queues, linked lists, trees, binary
More informationProgramming Languages Third Edition. Chapter 7 Basic Semantics
Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol
More informationLinked List Implementation of Queues
Outline queue implementation: linked queue application of queues and stacks: data structure traversal double-ended queues application of queues: simulation of an airline counter random numbers recursion
More informationCS 220: Discrete Structures and their Applications. graphs zybooks chapter 10
CS 220: Discrete Structures and their Applications graphs zybooks chapter 10 directed graphs A collection of vertices and directed edges What can this represent? undirected graphs A collection of vertices
More informationimplementing the breadth-first search algorithm implementing the depth-first search algorithm
Graph Traversals 1 Graph Traversals representing graphs adjacency matrices and adjacency lists 2 Implementing the Breadth-First and Depth-First Search Algorithms implementing the breadth-first search algorithm
More informationCopyright 2000, Kevin Wayne 1
Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. Directed
More informationA6-R3: DATA STRUCTURE THROUGH C LANGUAGE
A6-R3: DATA STRUCTURE THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be answered in the TEAR-OFF
More information3.1 Basic Definitions and Applications
Graphs hapter hapter Graphs. Basic efinitions and Applications Graph. G = (V, ) n V = nodes. n = edges between pairs of nodes. n aptures pairwise relationship between objects: Undirected graph represents
More informationLecture 24 Notes Search in Graphs
Lecture 24 Notes Search in Graphs 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, André Platzer, Rob Simmons, Penny Anderson 1 Introduction In this lecture, we will discuss the
More informationCS301 - Data Structures Glossary By
CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm
More information1 The Shortest Path Problem
CS161 Lecture 11 Single Source Shortest Paths Scribed by: Romil Verma (2015), Virginia Date: May 8, 2016 1 The Shortest Path Problem In this lecture, we ll discuss the shortest path problem. Assume we
More informationStacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)
Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria
More informationPreface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS
Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...
More informationLecture 1. 1 Notation
Lecture 1 (The material on mathematical logic is covered in the textbook starting with Chapter 5; however, for the first few lectures, I will be providing some required background topics and will not be
More informationDiscrete Mathematics for CS Spring 2008 David Wagner Note 13. An Introduction to Graphs
CS 70 Discrete Mathematics for CS Spring 2008 David Wagner Note 13 An Introduction to Graphs Formulating a simple, precise specification of a computational problem is often a prerequisite to writing a
More informationPostfix (and prefix) notation
Postfix (and prefix) notation Also called reverse Polish reversed form of notation devised by mathematician named Jan Łukasiewicz (so really lü-kä-sha-vech notation) Infix notation is: operand operator
More informationAlgorithm Design and Analysis
Algorithm Design and Analysis LECTURE 5 Exploring graphs Adam Smith 9/5/2008 A. Smith; based on slides by E. Demaine, C. Leiserson, S. Raskhodnikova, K. Wayne Puzzles Suppose an undirected graph G is connected.
More informationLecture 3: Graphs and flows
Chapter 3 Lecture 3: Graphs and flows Graphs: a useful combinatorial structure. Definitions: graph, directed and undirected graph, edge as ordered pair, path, cycle, connected graph, strongly connected
More informationStacks, Queues (cont d)
Stacks, Queues (cont d) CSE 2011 Winter 2007 February 1, 2007 1 The Adapter Pattern Using methods of one class to implement methods of another class Example: using List to implement Stack and Queue 2 1
More informationByzantine Consensus in Directed Graphs
Byzantine Consensus in Directed Graphs Lewis Tseng 1,3, and Nitin Vaidya 2,3 1 Department of Computer Science, 2 Department of Electrical and Computer Engineering, and 3 Coordinated Science Laboratory
More informationCOURSE: DATA STRUCTURES USING C & C++ CODE: 05BMCAR17161 CREDITS: 05
COURSE: DATA STRUCTURES USING C & C++ CODE: 05BMCAR17161 CREDITS: 05 Unit 1 : LINEAR DATA STRUCTURES Introduction - Abstract Data Types (ADT), Arrays and its representation Structures, Stack, Queue, Circular
More informationCS 161 Lecture 11 BFS, Dijkstra s algorithm Jessica Su (some parts copied from CLRS) 1 Review
1 Review 1 Something I did not emphasize enough last time is that during the execution of depth-firstsearch, we construct depth-first-search trees. One graph may have multiple depth-firstsearch trees,
More informationSection Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees
Chapter 11 Copyright McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education. Chapter Summary Introduction to Trees Applications
More informationMinimum Spanning Trees Ch 23 Traversing graphs
Next: Graph Algorithms Graphs Ch 22 Graph representations adjacency list adjacency matrix Minimum Spanning Trees Ch 23 Traversing graphs Breadth-First Search Depth-First Search 11/30/17 CSE 3101 1 Graphs
More informationSome Extra Information on Graph Search
Some Extra Information on Graph Search David Kempe December 5, 203 We have given basic definitions of graphs earlier in class, and talked about how to implement them. We had also already mentioned paths,
More information12/5/17. trees. CS 220: Discrete Structures and their Applications. Trees Chapter 11 in zybooks. rooted trees. rooted trees
trees CS 220: Discrete Structures and their Applications A tree is an undirected graph that is connected and has no cycles. Trees Chapter 11 in zybooks rooted trees Rooted trees. Given a tree T, choose
More informationCSE 373 MAY 10 TH SPANNING TREES AND UNION FIND
CSE 373 MAY 0 TH SPANNING TREES AND UNION FIND COURSE LOGISTICS HW4 due tonight, if you want feedback by the weekend COURSE LOGISTICS HW4 due tonight, if you want feedback by the weekend HW5 out tomorrow
More informationinfix expressions (review)
Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure
More informationElementary Graph Algorithms. Ref: Chapter 22 of the text by Cormen et al. Representing a graph:
Elementary Graph Algorithms Ref: Chapter 22 of the text by Cormen et al. Representing a graph: Graph G(V, E): V set of nodes (vertices); E set of edges. Notation: n = V and m = E. (Vertices are numbered
More informationGraphs. The ultimate data structure. graphs 1
Graphs The ultimate data structure graphs 1 Definition of graph Non-linear data structure consisting of nodes & links between them (like trees in this sense) Unlike trees, graph nodes may be completely
More informationIntroduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms
Introduction Problem Solving on Computer Data Structures (collection of data and relationships) Algorithms 1 Objective of Data Structures Two Goals: 1) Identify and develop useful high-level data types
More informationLIFO : Last In First Out
Introduction Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stack is a data structure that is particularly useful in applications involving reversing.
More informationCOSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor
COSC160: Data Structures: Lists and Queues Jeremy Bolton, PhD Assistant Teaching Professor Outline I. Queues I. FIFO Queues I. Usage II. Implementations II. LIFO Queues (Stacks) I. Usage II. Implementations
More informationlecture27: Graph Traversals
lecture27: Largely based on slides by Cinda Heeren CS 225 UIUC 25th July, 2013 Announcements mp7.1 extra credit due tomorrow night (7/26) Code challenge tomorrow night (7/26) at 6pm in 0224 lab hash due
More informationCSE 331: Introduction to Algorithm Analysis and Design Graphs
CSE 331: Introduction to Algorithm Analysis and Design Graphs 1 Graph Definitions Graph: A graph consists of a set of verticies V and a set of edges E such that: G = (V, E) V = {v 0, v 1,..., v n 1 } E
More informationCS302 - Data Structures using C++
CS302 - Data Structures using C++ Topic: Graphs - Introduction Kostas Alexis Terminology In the context of our course, graphs represent relations among data items G = {V,E} A graph is a set of vertices
More informationγ(ɛ) (a, b) (a, d) (d, a) (a, b) (c, d) (d, d) (e, e) (e, a) (e, e) (a) Draw a picture of G.
MAD 3105 Spring 2006 Solutions for Review for Test 2 1. Define a graph G with V (G) = {a, b, c, d, e}, E(G) = {r, s, t, u, v, w, x, y, z} and γ, the function defining the edges, is given by the table ɛ
More information22.3 Depth First Search
22.3 Depth First Search Depth-First Search(DFS) always visits a neighbour of the most recently visited vertex with an unvisited neighbour. This means the search moves forward when possible, and only backtracks
More informationLECTURE 17 GRAPH TRAVERSALS
DATA STRUCTURES AND ALGORITHMS LECTURE 17 GRAPH TRAVERSALS IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD STRATEGIES Traversals of graphs are also called searches We can use either breadth-first
More informationPriority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.
Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority
More informationGraphs and trees come up everywhere. We can view the internet as a graph (in many ways) Web search views web pages as a graph
Graphs and Trees Graphs and trees come up everywhere. We can view the internet as a graph (in many ways) who is connected to whom Web search views web pages as a graph Who points to whom Niche graphs (Ecology):
More informationModule 11: Additional Topics Graph Theory and Applications
Module 11: Additional Topics Graph Theory and Applications Topics: Introduction to Graph Theory Representing (undirected) graphs Basic graph algorithms 1 Consider the following: Traveling Salesman Problem
More informationCSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion
CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,
More informationSubprograms, Subroutines, and Functions
Subprograms, Subroutines, and Functions Subprograms are also called subroutines, functions, procedures and methods. A function is just a subprogram that returns a value; say Y = SIN(X). In general, the
More informationCS 125 Section #6 Graph Traversal and Linear Programs 10/13/14
CS 125 Section #6 Graph Traversal and Linear Programs 10/13/14 1 Depth first search 1.1 The Algorithm Besides breadth first search, which we saw in class in relation to Dijkstra s algorithm, there is one
More informationCSE 100: GRAPH ALGORITHMS
CSE 100: GRAPH ALGORITHMS 2 Graphs: Example A directed graph V5 V = { V = E = { E Path: 3 Graphs: Definitions A directed graph V5 V6 A graph G = (V,E) consists of a set of vertices V and a set of edges
More informationLecture 5: Graphs. Rajat Mittal. IIT Kanpur
Lecture : Graphs Rajat Mittal IIT Kanpur Combinatorial graphs provide a natural way to model connections between different objects. They are very useful in depicting communication networks, social networks
More information