Readings and Homework PRIORITY QUEUES AND HEAPS. The Bag Interface. Stacks and Queues as Lists. Priority Queue. Priority Queue Examples 10/28/2013

Similar documents
Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

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

Binary Heaps. CSE 373 Data Structures

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

Cpt S 223. School of EECS, WSU

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

Binary Heap Algorithms

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Ordered Lists and Binary Trees

From Last Time: Remove (Delete) Operation

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

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:

Binary Search Trees (BST)

Big Data and Scripting. Part 4: Memory Hierarchies

Data Structures Fibonacci Heaps, Amortized Analysis

Algorithms and Data Structures Written Exam Proposed SOLUTION

Full and Complete Binary Trees

Data Structures and Algorithms

6 March Array Implementation of Binary Trees

Algorithms and Data Structures

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

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

Chapter 14 The Binary Search Tree

TREE BASIC TERMINOLOGIES

How To Create A Tree From A Tree In Runtime (For A Tree)

Exam study sheet for CS2711. List of topics

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

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

Data Structures in the Java API

Lecture Notes on Binary Search Trees

Analysis of a Search Algorithm

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

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Programming with Data Structures

Lecture 6: Binary Search Trees CSCI Algorithms I. Andrew Rosenberg

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Binary Search Trees CMPSC 122

Converting a Number from Decimal to Binary

CompSci-61B, Data Structures Final Exam

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

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

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

Binary Trees. Wellesley College CS230 Lecture 17 Thursday, April 5 Handout #28. PS4 due 1:30pm Tuesday, April

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.

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

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

Algorithms and Data Structures

Sequential Data Structures

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

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

Sample Questions Csci 1112 A. Bellaachia

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

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

Lecture Notes on Binary Search Trees

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

Why Use Binary Trees?

7.1 Our Current Model

PES Institute of Technology-BSC QUESTION BANK

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

CS711008Z Algorithm Design and Analysis

Symbol Tables. Introduction

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

S. Muthusundari. Research Scholar, Dept of CSE, Sathyabama University Chennai, India Dr. R. M.

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Common Data Structures

B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

International Journal of Software and Web Sciences (IJSWS)

Analysis of Algorithms I: Binary Search Trees

Analysis of Algorithms I: Optimal Binary Search Trees

Data Structures Using C++

Chapter 8: Bags and Sets

Persistent Binary Search Trees

Data Structures and Data Manipulation

Lecture 2: Data Structures Steven Skiena. skiena

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

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

CSE 326: Data Structures B-Trees and B+ Trees

LINKED DATA STRUCTURES

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Part 3: GridWorld Classes and Interfaces

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

STACKS,QUEUES, AND LINKED LISTS

Module 2 Stacks and Queues: Abstract Data Types

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

The ADT Binary Search Tree

A Comparison of Dictionary Implementations

Class Notes CS Creating and Using a Huffman Code. Ref: Weiss, page 433

Linked Lists Linked Lists, Queues, and Stacks

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!

Data Structure [Question Bank]

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Introduction to Data Structures

CmpSci 187: Programming with Data Structures Spring 2015

Transcription:

1 Readings and Homework Read Chapter to learn about heaps PRIORITY QUEUES AND HEAPS Lecture 1 CS10 Fall 013 Salespeople often make matrices that show all the great features of their product that the competitor s product lacks. Try this for a heap versus a BST. First, try and sell someone on a BST: List some desirable properties of a BST that a heap lacks. Now be the heap salesperson: List some good things about heaps that a BST lacks. Can you think of situations where you would favor one over the other? With ZipUltra heaps, you ve got it made in the shade my friend! The Bag Interface Stacks and Queues as Lists 3 A Bag: interface Bag<E> { void insert(e obj); E ; //extract some element boolean isempty(); Examples: Stack, Queue, PriorityQueue Stack (LIFO) implemented as list, from front of list Queue (FIFO) implemented as list on back of list, from front of list All Bag operations are O(1) first 10 1 last Priority Queue A Bag in which data items are Comparable lesser elements (as determined by compareto()) have higher priority returns the element with the highest priority = least in the compareto() ordering break ties arbitrarily Priority Queue Examples Scheduling jobs to run on a computer default priority = arrival time priority can be changed by operator Scheduling events to be processed by an event handler priority = time of occurrence Airline check-in first class, business class, coach FIFO within each class 1

7 java.util.priorityqueue<e> boolean add(e e) {... //insert an element (insert) void clear() {... //remove all elements E peek() {... //return min element without removing //(null if empty) E poll() {... //remove min element (extract) //(null if empty) int size() {... Priority Queues as Lists Maintain as unordered list puts new element at front O(1) must search the list O(n) Maintain as ordered list must search the list O(n) gets element at front O(1) In either case, O(n ) to process n elements Can we do better? 9 Important Special Case Fixed number of priority levels 0,...,p 1 FIFO within each level Example: airline check-in insert in appropriate queue O(1) must find a nonempty queue O(p) 10 Heaps Aheap is a concrete data structure that can be used to implement priority queues Gives better complexity than either ordered or unordered list implementation: : O(log n) : O(log n) O(n log n) to process n elements Do not confuse with heap memory, where the Java virtual machine allocates space for objects different usage of the word heap 11 Heaps 1 Heaps Binary tree with data at each node Satisfies the Heap Order Invariant: Least element in any subtree is always found at the root of that subtree The least (highest priority) element of any subtree is found at the root of that subtree Size of the heap is fixed at n. (But can usually double n if heap fills up) 1 3 Note:, 0 < 3: we can often find smaller elements deeper in the tree!

13 Examples of Heaps 1 Balanced Heaps Ages of people in family tree parent is always older than children, but you can have an uncle who is younger than you Salaries of employees of a company bosses generally make more than subordinates, but a VP in one subdivision may make less than a Project Supervisor in a different subdivision These add two restrictions: 1. Any node of depth < d 1 has exactly children, where d is the height of the tree implies that any two maximal paths (path from a root to a leaf) are of length d or d 1, and the tree has at least d nodes All maximal paths of length d are to the left of those of length d 1 Example of a Balanced Heap Store in an ArrayList or Vector 1 1 1 Elements of the heap are stored in the array in order, going across each level from left to right, top to bottom 3 The children of the node at array index n are found at n + 1 and n + d = 3 The parent of node n is found at (n 1)/ Store in an ArrayList or Vector Store in an ArrayList or Vector 17 1 0 1 1 3 3 7 9 10 11 children of node n are found at n + 1 and n + 0 1 1 3 3 9 7 10 11 3 10 0 0 1 3 7 9 10 11 1 3 children of node n are found at n + 1 and n + 3

0 Put the new element at the end of the array If this violates heap order because it is smaller than its parent, swap it with its parent 1 Continue swapping it up until it finds its rightful place The heap invariant is maintained! 3 1 1 3 3 3 1 3 1 3

1 3 1 3 7 1 1 3 3 9 30 Time is O(log n), since the tree is balanced size of tree is exponential as a function of depth 1 depth of tree is logarithmic as a function of size 3

31 3 class PriorityQueue<E> extends java.util.vector<e> { public void insert(e obj) { super.add(obj); //add new element to end of array rotateup(size() - 1); private void rotateup(int index) { if (index == 0) return; int parent = (index - 1)/; if (elementat(parent).compareto(elementat(index)) <= 0) return; swap(index, parent); rotateup(parent); Remove the least element it is at the root This leaves a hole at the root fill it in with the last element of the array If this violates heap order because the root element is too big, swap it down with the smaller of its children Continue swapping it down until it finds its rightful place The heap invariant is maintained! 33 3 1 3 1 3 3 3 1 3 1 3

37 3 1 1 3 3 39 0 1 1 3 3 1 0 1 1 3 3 3 10 7

3 0 1 1 3 0 3 3 10 3 10 1 1 10 3 10 3 3 0 3 0 7 Time is O(log n), since the tree is balanced public E { if (size() == 0) return null; E temp = elementat(0); setelementat(elementat(size() - 1), 0); setsize(size() - 1); rotatedown(0); return temp; private void rotatedown(int index) { int child = *(index + 1); //right child if (child >= size() elementat(child - 1).compareTo(elementAt(child)) < 0) child -= 1; if (child >= size()) return; if (elementat(index).compareto(elementat(child)) <= 0) return; swap(index, child); rotatedown(child);

9 HeapSort 0 PQ Application: Simulation Given a Comparable[] array of length n, Put all n elements into a heap O(n log n) Repeatedly get the min O(n log n) public static void heapsort(comparable[] a) { PriorityQueue<Comparable> pq = new PriorityQueue<Comparable>(a); for (int i = 0; i < a.length; i++) { a[i] = pq.; Example: Probabilistic model of bank-customer arrival times and transaction times, how many tellers are needed? Assume we have a way to generate random inter-arrival times Assume we have a way to generate transaction times Can simulate the bank to get some idea of how long customers must wait Time-Driven Simulation Check at each tick to see if any event occurs Event-Driven Simulation Advance clock to next event, skipping intervening ticks This uses a PQ! 9