CPS 100, Fall 2009 12.1 YAQ, YAQ, haha! (Yet Another Queue) l What is the dequeue policy for a Queue?  Why do we implement Queue with LinkedList Interface.

Slides:



Advertisements
Similar presentations
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Advertisements

Advanced Data Structures Chapter 16. Priority Queues Collection of elements each of which has a priority. Does not maintain a first-in, first-out discipline.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2004 Heaps and heap sort  complete tree, heap property  min-heaps & max-heaps  heap operations:
Midterm 2 Overview Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 TCSS 342, Winter 2005 Lecture Notes Priority Queues and Heaps Weiss Ch. 21, pp
Priority Queues. Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out –The “smallest” element.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
1 Hash Tables  a hash table is an array of size Tsize  has index positions 0.. Tsize-1  two types of hash tables  open hash table  array element type.
1 CSC 421: Algorithm Design Analysis Spring 2014 Transform & conquer  transform-and-conquer approach  presorting  balanced search trees, heaps  Horner's.
CPS 100e, Spring Day, Week, Month Overview l Backtracking p/review  Boggle  APT l Assignment review  Boggle  APT l PQ Overview.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Chapter 11 Heap. Overview ● The heap is a special type of binary tree. ● It may be used either as a priority queue or as a tool for sorting.
CPS 100, Fall PF-AT-EOS l Data compression  Seriously important, why? l Priority Queue  Seriously important, why? l Assignment overview  Huff.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
CompSci 100E 24.1 Data Compression  Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  What property of MP3 was a significant factor.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
CPS Heaps, Priority Queues, Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  What property of MP3 was a significant.
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
Heaps & Priority Queues
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R3. Priority Queues.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
CSE 373: Data Structures and Algorithms Lecture 11: Priority Queues (Heaps) 1.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
CompSci 100e 8.1 Plan for the Course! l Understand Huffman Coding  Data compression  Priority Queues  Bits and Bytes  Greedy Algorithms l Algorithms.
CS6045: Advanced Algorithms Sorting Algorithms. Heap Data Structure A heap (nearly complete binary tree) can be stored as an array A –Root of tree is.
1. What is it? It is a queue that access elements according to their importance value. Eg. A person with broken back should be treated before a person.
CPS Heaps, Priority Queues, Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  Why is compression important?
CS 367 Introduction to Data Structures Lecture 8.
Priority Queues and Heaps Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University.
Priority Queues CS 110: Data Structures and Algorithms First Semester,
Priority Queues CS /02/05 L7: PQs Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
1 CSC 421: Algorithm Design Analysis Spring 2013 Transform & conquer  transform-and-conquer approach  presorting  balanced search trees, heaps  Horner's.
Sorting With Priority Queue In-place Extra O(N) space
Heaps (8.3) CSE 2011 Winter May 2018.
CSCE 210 Data Structures and Algorithms
Data Compression Compression is a high-profile application
Priority Queues © 2010 Goodrich, Tamassia Priority Queues 1
Hashing Exercises.
Compsci 201 Priority Queues & Autocomplete
Heaps, Priority Queues, Compression
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
CMSC 341: Data Structures Priority Queues – Binary Heaps
Part-D1 Priority Queues
i206: Lecture 14: Heaps, Graphs intro.
CSE 373: Data Structures and Algorithms
Priority Queues & Heaps
CSE 373 Data Structures and Algorithms
CSC 380: Design and Analysis of Algorithms
Priority Queues & Heaps
Scoreboard What else might we want to do with a data structure?
Presentation transcript:

CPS 100, Fall YAQ, YAQ, haha! (Yet Another Queue) l What is the dequeue policy for a Queue?  Why do we implement Queue with LinkedList Interface and class in java.util  Can we remove an element other than first? l How does queue help word-ladder/shortest path?  First item enqueued/added is the one we want  What if different element is “best”? l PriorityQueue has a different dequeue policy  Best item is dequeued, queue manages itself to ensure operations are efficient

CPS 100, Fall PriorityQueue raison d’être l Algorithms Using PQ for efficiency  Shortest Path: Mapquest/Garmin to Internet Routing How is this like word-ladder? How different?  Connecting all outlets in a house with minimal wiring Minimal spanning tree in graph  Optimal A* search, game-playing, AI, Can’t explore entire search space, can estimate good move l Data compression facilitated by priority queue  Alltime best assignment in a Compsci 100 course? Subject to debate, of course  From A-Z, soup-to-nuts, bits to abstractions

CPS 100, Fall PQ Application: Data Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  What property of MP3 was a significant factor in what made Napster work (why did Napster ultimately fail?)  Who invented Napster, how old, when? l Why do we care?  Secondary storage capacity doubles every year  Disk space fills up quickly on every computer system  More data to compress than ever before  Will we ever need to stop worrying about storage?

CPS 100, Fall More on Compression l Different compression techniques .mp3 files and.zip files? .gif and.jpg?  Lossless and lossy l Impossible to compress/lossless everything: Why? l Lossy methods  Good for pictures, video, and audio (JPEG, MPEG, etc.) l Lossless methods  Run-length encoding, Huffman, LZW, … 

CPS 100, Fall Priority Queue l Compression motivates ADT priority queue  Supports two basic operations add/insert -– an element into the priority queue remove/delete – the minimal element from the priority queue  Implementations allow getmin/peek as well as delete Analogous to top/pop, peek/dequeue in stacks, queues l Think about implementing the ADT, choices?  Add compared to min/remove  Balanced search tree is ok, but can we do better?

CPS 100, Fall Priority Queue sorting l See PQDemo.java,  code below sorts, complexity? String[] array = {...}; // array filled with data PriorityQueue pq = new PriorityQueue (); for(String s : array) pq.add(s); for(int k=0; k < array.length; k++){ array[k] = pq.remove(); } l Bottlenecks, operations in code above  Add words one-at-a-time to PQ v. all-at-once  What if PQ is an array, add or remove fast/slow?  We’d like PQ to have tree characteristics, why?

CPS 100, Fall Priority Queue top-M sorting l What if we have lots and lots and lots of data  code below sorts top-M elements, complexity? Scanner s = … // initialize; PriorityQueue pq = new PriorityQueue (); while (s.hasNext()) { pq.add(s.next()); if (pq.size() > M) pq.remove(); } l What’s advantageous about this code?  Store everything and sort everything?  Store everything, sort first M?  What is complexity of sort: O(n log n)

CPS 100, Fall Priority Queue implementations l Priority queues: average and worst case Insert average Getmin (delete) Insert worst Getmin (delete) Unsorted list Sorted list Search tree Balanced tree Heap log n O(n) O(1)log n O(n)O(1)O(n)O(1) O(n)O(1)O(n)O(1) l Heap has O(n) build heap from n elements

CPS 100, Fall PriorityQueue.java (Java 5+) l What about objects inserted into pq?  Comparable, e.g., essentially sortable  How can we change what minimal means?  Implementation uses heap, tree stored in an array l Use a Comparator for comparing entries we can make a min-heap act like a max-heap, see PQDemo  Where is class Comparator declaration? How used?  What if we didn't know about Collections.reverseOrder? How do we make this ourselves?

CPS 100, Fall Big-Oh and a tighter look at inserts l log(1) + log(2) + log(3) + … + log(n)  Property of logs, log(a) + log(b) = log(a*b)  log(1*2*3*…*n) = log(n!) l We can show using Sterling’s formula: l log(n!) = c 1 *log(n) + nlog(n) – c 2 *n l We can get O(n log n) easily, this goes tight, lower,  n log n) as well

CPS 100, Fall Priority Queue implementation l Heap data structure is fast and reasonably simple  Why not use inheritance hierarchy as was used with Map?  Trade-offs when using HashMap and TreeMap: Time, space, ordering properties, TreeMap support? l Changing comparison when calculating priority?  Create object to replace, or in lieu of compareTo Comparable interface compares this to passed object Comparator interface compares two passed objects  Both comparison methods: compareTo() and compare() Compare two objects (parameters or self and parameter) Returns –1, 0, +1 depending on

CPS 100, Fall Creating Heaps l Heap: array-based implementation of binary tree used for implementing priority queues:  add/insert, peek/getmin, remove/deletemin, O(???) l Array minimizes storage (no explicit pointers), faster too, contiguous (cache) and indexing l Heap has shape property and heap/value property  shape: tree filled at all levels (except perhaps last) and filled left-to-right (complete binary tree)  each node has value smaller than both children

CPS 100, Fall Array-based heap l store “node values” in array beginning at index 1 l for node with index k  left child: index 2*k  right child: index 2*k+1 l why is this conducive for maintaining heap shape? l what about heap property? l is the heap a search tree? l where is minimal node? l where are nodes added? deleted?

CPS 100, Fall Thinking about heaps Where is minimal element?  Root, why? l Where is maximal element?  Leaves, why? l How many leaves are there in an N-node heap (big-Oh)?  O(n), but exact? l What is complexity of find max in a minheap? Why?  O(n), but ½ N? l Where is second smallest element? Why?  Near root?

CPS 100, Fall Adding values to heap l to maintain heap shape, must add new value in left-to-right order of last level  could violate heap property  move value “up” if too small l change places with parent if heap property violated  stop when parent is smaller  stop when root is reached l pull parent down, swapping isn’t necessary (optimization) insert 8 bubble 8 up

CPS 100, Fall Adding values, details (pseudocode) void add(Object elt) { // add elt to heap in myList myList.add(elt); int loc = myList.size()-1; while (1 < loc && elt < myList.get(loc/2)){ myList.set(loc,myList.get(loc/2)); loc = loc/2; // go to parent } // what’s true here? myList.set(loc,elt); } array myList

CPS 100, Fall Removing minimal element l Where is minimal element?  If we remove it, what changes, shape/property? l How can we maintain shape?  “last” element moves to root  What property is violated? l After moving last element, subtrees of root are heaps, why?  Move root down (pull child up) does it matter where? l When can we stop “re- heaping”?  Less than both children  Reach a leaf

CPS 100, Fall Anita Borg “Dr. Anita Borg tenaciously envisioned and set about to change the world for women and for technology. … she fought tirelessly for the development technology with positive social and human impact.” l “Anita Borg sought to revolutionize the world and the way we think about technology and its impact on our lives.” l ch?v=1yPxd5jqz_Q ch?v=1yPxd5jqz_Q