Programming with Data Structures



Similar documents
CmpSci 187: Programming with Data Structures Spring 2015

DATA STRUCTURE - QUEUE

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Sequential Data Structures

Analysis of a Search Algorithm

Common Data Structures

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

Chapter 3: Restricted Structures Page 1

STACKS,QUEUES, AND LINKED LISTS

DATA STRUCTURE - STACK

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Lecture Notes on Linear Search

St S a t ck a ck nd Qu Q eue 1

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Universidad Carlos III de Madrid

Parallel Programming

Module 2 Stacks and Queues: Abstract Data Types

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Algorithms and Data Structures Written Exam Proposed SOLUTION

Data Structures and Algorithms Lists

Chapter 8: Bags and Sets

Application of Stacks: Postfix Expressions Calculator (cont d.)

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Algorithms and Data Structures

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Introduction to Data Structures

Linked Lists Linked Lists, Queues, and Stacks

Lecture Notes on Binary Search Trees

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

! stack, queue, priority queue, dictionary, sequence, set e.g., a Stack is a list implements a LIFO policy on additions/deletions.

Lecture Notes on Stacks & Queues

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

1 Description of The Simpletron

Lab Experience 17. Programming Language Translation

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Level 3 Develop software using Java (7266/ )

Part 3: GridWorld Classes and Interfaces

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

CompSci-61B, Data Structures Final Exam

User guide for the Error & Warning LabVIEW toolset

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Approach of Unit testing with the help of JUnit

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

14.1 Rent-or-buy problem

Data Structures Fibonacci Heaps, Amortized Analysis

Node-Based Structures Linked Lists: Implementation

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Introduction to Data Structures and Algorithms

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Big O and Limits Abstract Data Types Data Structure Grand Tour.

Abstract Data Types. Chapter 2

14 Stacks, Queues, And Linked Lists

Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm

LINKED DATA STRUCTURES

The ADT Binary Search Tree

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

Basic Data Structures and Algorithms

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

CMSC 202H. ArrayList, Multidimensional Arrays

Dynamic Programming Problem Set Partial Solution CMPSC 465

Vieta s Formulas and the Identity Theorem

3.2. Solving quadratic equations. Introduction. Prerequisites. Learning Outcomes. Learning Style

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Data Structures and Algorithms

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

arrays C Programming Language - Arrays

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Lecture Notes on Binary Search Trees

Java Interview Questions and Answers

Lecture 12 Doubly Linked Lists (with Recursion)

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Binary Heap Algorithms

CMPSCI 250: Introduction to Computation. Lecture #19: Regular Expressions and Their Languages David Mix Barrington 11 April 2013

Lecture 2. Binary and Hexadecimal Numbers

Algorithms and Data Structures

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

CS 2412 Data Structures. Chapter 3 Queues

COMPUTER SCIENCE. Paper 1 (THEORY)

Efficient Data Structures for Decision Diagrams

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

7.6 Approximation Errors and Simpson's Rule

Midterm Exam CMPSCI 453: Computer Networks Fall 2011 Prof. Jim Kurose

MOST FREQUENTLY ASKED INTERVIEW QUESTIONS. 1. Why don t you tell me about yourself? 2. Why should I hire you?

5544 = = = Now we have to find a divisor of 693. We can try 3, and 693 = 3 231,and we keep dividing by 3 to get: 1

Heaps & Priority Queues in the C++ STL 2-3 Trees

Overview. What is software testing? What is unit testing? Why/when to test? What makes a good test? What to test?

Transcription:

Programming with Data Structures CMPSCI 187 Spring 2016 Please find a seat Try to sit close to the center (the room will be pretty full!) Turn off or silence your mobile phone Turn off your other internet-enabled devices 1

Array-Based Queue We ve learned to implement the queue using a linked list. Now let s look at an array-based implementation. To begin, we use an array with fixed capacity to store queue elements. We assume element 0 is always the front, and use an rear index to point to the last element in the queue. To enqueue, we append the new element at the end, and increment the rear index; to dequeue, we return element 0, and move all remaining elements to the left by one position, then decrement the rear index.

Array-Based Queue: Fixed Front Start with an empty queue with capacity 5 After enqueuing A, B, C, and D. Dequeue the front element. Move the remaining elements to the left by one spot.

Clicker Question #1 Using the algorithm in the previous slides (i.e. fixed front array-based queue), what s the running cost of the enqueue and dequeue operations. Assume the queue has N elements, and a capacity of M? (a) enqueue is O(1), dequeue is O(M) (b)enqueue is O(1), dequeue is O(N) (c) enqueue is O(N), dequeue is O(N) (d)enqueue is O(M), dequeue is O(1) (e) enqueue is O(M), dequeue is O(N)

A Circular Queue With fixed front design, dequeue takes O(N), which is inefficient. To make it more efficient, we remove the requirement that the front is always at index 0. Instead, we will allow it to float. We keep a front index to point to the current front element, and a rear index to point to the current rear. To enqueue, we add a new item at the rear and increment the rear index. To dequeue, we remove the front item and increment the front index.

enqueue A enqueue B enqueue C dequeue

A Circular Queue Note that after dequeuing an element, that spot (e.g. index 0) becomes available. So if you continue to enqueue, (say D, E, F), element F can be stored at index 0. Imagine the array is circular (i.e. the end of the array wraps back to the beginning of the array). Hence it s called a [M-2] [M-1] [0] [1] [2] circular queue. A circular queue of capacity M

enqueue L A Circular Queue

A Circular Queue Considering the wrap-around, how do we increment the rear index when enqueuing? if (rear == capacity - 1) rear = 0; else rear = rear + 1; Is there a simpler way? Hint: using modulo?

A Circular Queue Considering the wrap-around, how do we increment the rear index when enqueuing? rear = (rear + 1) % capacity; Verify if it s correct when rear is (capacity - 1). In general, when you do x % capacity, as long as x is non-negative, the result is always between 0 and (capacity - 1). Careful: if x is negative, the result will be negative! this is not true in other languages (python etc).

Clicker Question #2 If we want to decrement the rear index, which of the following code is correct, assuming a circular queue? (a) rear = (rear - 1); (b) rear = (rear - 1) % capacity; (c) rear = (rear - 1 + capacity) % capacity; (d) rear = (rear - 1) % capacity + 1; (e) rear = (rear - 1) % capacity + capacity;

A Circular Queue As front index points to the front element, and rear index points to the rear element, when they are equal, there is exactly one element. For example, when they are both equal to 0 (or both equal to 1 and so on), there is one element. At the beginning, when the queue is empty, we initialize front = 0, and rear = capacity-1. This creates ambiguity, why? Thank about the values of front and rear when the queue is full. How do we address this?

A Circular Queue At any point, the elements starting from the front index to the rear index (in a circular fashion) constitute the queue elements.

Clicker Question #3 Assuming the number of queue elements is less than capacity (i.e. ignoring the ambiguity), which of the following expressions correctly calculates the number of elements in the queue? (Hint: consider some different combinations of front and rear). (a) (rear - front) % capacity (b) (rear - front + 1) % capacity (c) (front - rear + 1) % capacity (d) none of the above

Coding the Circular Queue public class ArrayBndQueue<T> implements BQI<T> { protected final int DEFCAP = 100; protected T[] queue; protected int numelements = 0; protected int front = 0, rear; public ArrayBndQueue(int maxsize) { // compiler warning queue = (T[]) new Object[maxSize]; // virtual position -1 rear = maxsize - 1; } public ArrayBndQueue() { this (DEFCAP); }

Coding Queue Operations public boolean isempty() { return (numelements == 0); } public boolean isfull() { return (numelements == queue.length); }

Coding Queue Operations public void enqueue (T element) { if (isfull()) throw new QOE( add to full queue ); else { rear = (rear + 1) % queue.length; queue[rear] = element; numelements++; } }

Coding Queue Operations public T dequeue () { if (isempty()) throw new QUE( dequeue from empty ); else { T toreturn = queue[front]; queue[front] = null; front = (front + 1) % queue.length; numelements--; return toreturn; } }

Java s ArrayList Class It would be nice if the array capacity is not fixed! At the end of the Linked List lecture, we briefly mentioned arrays that can dynamically expand, thus overcoming the fixed capacity limitation. Java provides several variable-length generic array structures, such as ArrayList<T>. It begins with some fixed capacity, but the capacity is reached, it copies itself into another array of twice the size, thus appears to be an array of unlimited size. 19

Java s ArrayList Class What s this doubling-the-capacity business? Let s say we have an initial ArrayList of capacity 10, and we keep adding elements to it. Adding the 11th element causes the ArrayList to allocate a new array of capacity 20, copy the existing 10 elements and the 11th element to the new array, then release the old array. Same thing happens as the 21th element is added. By the time we have 81 elements we have done four capacity expansions : to 20, 40, 80, and 160. 20

Java s ArrayList Class What s this doubling-the-capacity business? Let s say we have an initial ArrayList of capacity 10, and we keep adding elements to it. Adding the 11th element causes the ArrayList to allocate a new array of capacity 20, copy the existing 10 elements and the 11th element to the new array, then release the old array. Same thing happens as the 21th element is added. By the time we have 81 elements we have done four capacity expansions : to 20, 40, 80, and 160. 21

Unbounded Array-Based Queue You can use Java s ArrayList to implement Array-based Queue. Then it won t be bounded and hence can implement the UnboundedQueueInterface. Or you can write an array expand method yourself and call it inside the enqueue method. This way, the array will be expanded if enqueue is called when the array is already full. 22

Clicker Question #4 Assume a dynamic array has a capacity of 1 to begin with. Each time it expands, we double its capacity. Starting from an empty array, we add one element at a time, until there are N elements. How many times would the array have expanded? (number of times the expand method were called) (a) O(1) (b) O(N) (c) O(log N) (d) O(N^2)