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.

Slides:



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

Priority Queues CSC 172 SPRING 2002 LECTURE 16. Priority Queues Model Set with priorities associate with elements Priorites are comparable by a < operator.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Trees Chapter 8.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
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.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
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,
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
CS 46B: Introduction to Data Structures July 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
1 COP 3538 Data Structures with OOP Chapter 8 - Part 2 Binary Trees.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
data ordered along paths from root to leaf
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.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
P p Chapter 10 has several programming projects, including a project that uses heaps. p p This presentation shows you what a heap is, and demonstrates.
CSC 213 – Large Scale Programming Lecture 15: Heap-based Priority Queue.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
CSE373: Data Structures & Algorithms Lecture 6: Priority Queues Kevin Quinn Fall 2015.
Advanced Data Structure By Kayman 21 Jan Outline Review of some data structures Array Linked List Sorted Array New stuff 3 of the most important.
Intro. to Data Structures Chapter 6 Priority Queue (Heap) Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Priority Queue.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
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.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
CS 367 Introduction to Data Structures Lecture 8.
Priority Queues CS 110: Data Structures and Algorithms First Semester,
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
CSE373: Data Structures & Algorithms Lecture 8: AVL Trees and Priority Queues Linda Shapiro Spring 2016.
Lecture on Data Structures(Trees). Prepared by, Jesmin Akhter, Lecturer, IIT,JU 2 Properties of Heaps ◈ Heaps are binary trees that are ordered.
CSE373: Data Structures & Algorithms Priority Queues
CS 201 Data Structures and Algorithms
Hashing Exercises.
Source: Muangsin / Weiss
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.
Chapter 8 – Binary Search Tree
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Chapter 8 – Binary Search Tree
Find in a linked list? first last 7  4  3  8 NULL
CSE332: Data Abstractions Lecture 4: Priority Queues
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
CE 221 Data Structures and Algorithms
CSE 332: Data Structures Priority Queues – Binary Heaps Part II
Heaps and Priority Queues
CSC 380: Design and Analysis of Algorithms
CS 367 – Introduction to Data Structures
Priority Queues & Heaps
Tree.
Heaps.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

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 with minor wounds, even though he arrives later. Printer queue: less page should be selected to print first. But this does not happen in real life., 2

Priority Normally, small value is regarded as more important. If two item have equal priority, we may allow the item that exists longer in the queue to be more important. To compare elements, we use Comparable interface or Comparator Interface. 3

Comparator Interface Has method: compare(Object o1, Object o2) Has to be the same class or one is the subclass of the other. Return negative value if o1 is less than o2, positive value if o1 is more than o2, and 0 otherwise. 4

The interface for heap // Postcondition: return the number of items in this priority queue. // Postcondition: return true if this priority queue does not store any item, otherwise return false. // Postcondition: element is added to priority queue. 5

// Precondition: must not be an empty queue, otherwise it throws NoSuchElementException. // Postcondition: return the most important object from this PriorityQueue. // Precondition: must not be an empty queue, otherwise it throws NoSuchElementException. // Postcondition: remove and return the most important object from this PriorityQueue. 6

Many implementation choices exist Normal queue: no priority then? Array of queue (each queue for each priority): too much space to prepare if there are lots of possible priority. 7

Use ArrayList Easy to put members in order right away. Takes time to find a position to insert though. Many array elements have to be shifted after insertion or deletion. getMin is constant time because we can return the first array element right away. Add and remove take linear time, which is rather slow. We want better time. 8

Use LinkedList getMin and removeMin take constant time bacause we can return the front of the list right away. Add takes linear time, still need to search the position to add, but does not need element shifting. Remove takes constant time because we can just update pointers. 9

Use Comparable by default Linked List priority queue 10

public LinkedPQ (Comparator comp) { this(); comparator = comp; } // constructor with Comparator parameter public int size( ) { return list.size( ); } // method size public Object getMin ( ) { return list.getFirst( ); } // method getMin List methods in this chapter comes from LinkedList class in Java. 11

public Object removeMin( ) { return list.removeFirst( ); } // method removeFirst 12

why? 13

Wanna add this When loop fails itr.next() returns 4 and it moves. itr.add(element): The element is inserted immediately before the next element that would be returned by next, if any. So using itr.add(element) will insert in the wrong place. Therefore we need to call previous(). 14

protected int compare (Object elem1, Object elem2) { return (comparator==null ? ((Comparable)elem1).compareTo(elem2) : comparator.compare (elem1, elem2)); } // method compare If comparator = null, return elem1.compareTo (elem2) ; Otherwise, return comparator.compare (elem1, elem2) ; 15

An implementation using set Real structure is a tree. Use comparator too. 16

public void add (Object element) { set.add (element); } // method add public Object getMin ( ) { return set.first( ); } // method getMin public Object removeMin ( ) { Object temp = set.first( ); set.remove (set.first( )); return temp; } // method removeMin worstTime(n) for all these methods = O(log n). 17

Implement using real Heap public class Heap implements PriorityQueue { 18

Complete Binary tree 19

Heap is a complete binary tree It is either an empty tree, or A tree that has its minimum value in its root. (this kind of heap is called minHeap) Left and right subtree have to be heaps too. Heap is not a binary search tree! 20

Smallest value is at the root for every subtree. 21

Complete binary tree can be put into array It is easy to find child, parent. This is actually the tree from the previous page. 22

First, how to use Heap (smallest GPA is most important.) 23

24

25

// constructor receives string as input. toString should be implemented. // Postcondition: return integer that 0, depending on student’s GPA. 26

Let us see the class for heap. Actual implementation is array. 27

Index of a node’s child 28

Index of a node’s parent 29

Method of a Heap 30

Resize array, this is O(n) //add element to the back. // Postcondition: element is added to the heap. // worst case time = O(n) // average time = constant The real operation. Depends on avarage time of percolateUp 31

Let us add

Percolate up is Swapping 30 with its parent until parent has less value. We will get a heap when we finish. 33

Let us follow the movement. 34

We finally get a heap at the end of all swaps. 35

protected void percolateUp() { int parent; int child = size-1; Object temp; while (child>0) { parent = (child-1)/2; if(compare(heap[parent],heap[child]) <=0) break; temp = heap[parent]; heap[parent] = heap[child]; heap[child] = temp; child = parent; } // while } // method percolateUp Depend on the height of the tree. Worst case happens when we need to swap up to the root. // Postcondition: move the last element up the tree. The worst time is O(log n). The average time is constant. 36

Average time -percolateUp Let the new value be around the middle of existing values. Half array elements have greater value. This is a complete binary tree, therefore this half are leaves. Therefore we need to swap only once to get our value to the right place. This is why it is said to take a constant time. 37

public Object getMin() { if (size == 0) throw new NoSuchElementException( “ Empty ” ); return heap[0]; } // method getMin 38

removeMin() – Be careful! The tree may no longer be a complete binary tree. 39

//put the last element into the root. reduce size to prevent access of the array’s back // Precondition: must not be an empty queue or it throws NoSuchElementException. // Postcondition: remove the most important value from this queue. This object is returned as pur answer. // worst time = O(log n). Don’t need to do the exact swap. 40

when removeMin( ) is called, 48 will swap place with 26. Size will be reduced by 1. after that, percolateDown will be called

PercolateDown is Swapping 48 with its smallest child. We do it until no more swap can be done. We will get a legal heap in the end. 42

43

44

Now we finally get our heap. 45

protected void percolateDown(int start) { int parent = start; int child = 2*parent+1; Object temp; while (child<size) { if(child 0) child++; if (compare(heap[parent],heap[child]) <=0) break; temp = heap[child]; heap[child] = heap[parent]; heap[parent] = temp; parent = child; child= 2*parent+1; } // while } // method percolateDown If right child is smaller, change our “child”. Initially, let “child” be the left child. Child can’t be the last element because there will be no right child to compare. // Postcondition: heap arranged by moving the top element down the tree. Worst and average time is O(log n). 46

Try this and print the heap content. See if it is what you expected. 47

48

Let ’ s look Let ’ s say we want to compress file without losing any information Let M be the data that we want to compress. Let its size be characters. M contains only character a to character e. Let E be M after compression. 49

Normally, 1 character needs 16 bit to store character needs x16 bits. It is useful to know how to reduce the number of bits while maintaining the same information. 50

Try this The number of bits reduce to 300,000 51

Can it be reduced even more? The number of bits now <=300,000 But can mean either Aababa or cbda. Rather ambiguous. 52

How do we prevent ambiguity use prefix-free encoding. By creating a binary tree Left branch is 0. Right branch is 1. Character is at the leaves. 53

Therefore, there is no two characters on the same path (from root) a = 010 b = 11 c = 00 d = 10 e =

alternatives? Which scheme is best? Ans: frequently appear character should have small number of bits. 55

Create Huffman tree This is a binary tree of codes. but it is built using the frequency of characters in the message. Characters with high frequency will take less bits. 56

let us use the following example. A has 5000 B has c has d has e has

Put pair (character, frequency) into Priority Q Priority Q that we use, we will have the lowest frequency on top. Each node of our priority Q has left, right, parent of its own. In our example, the initial queue is (a:5000) (b: 10000) (c: 20000) (d: 31000) (e: 34000) Now let us build huffman tree. 58

Remove the two items with smallest frequency from the queue. The first one becomes the left branch, the second one becomes the right branch. The sum of their frequency becomes the root. a b Then we put the result back into the priority queue. The queue will now be ( :15000) (c: 20000) (d: 31000) (e: 34000) 0 1 A tree here 59

Remove the two front elements and do the same again. a b c When we put this tree back into the queue, we get -> (d: 31000) (e: 34000) ( : 35000) 60

Remove the two front elements and do the same again. d e This becomes a new tree. When we put this tree back into the queue, we get -> ( : 35000) ( : 65000) 61

We do the same again. priority Q will become (: ) a b c d e

Try creating a tree with this example. 63

Huffman class example Change input to huffman code. See next page. Sample code here is from Collin’s Java Collection Framework book. You don’t have to remember it. Just take it as an idea. 64

65

Array of leaves For quick access 66

Example a node for ‘c’ This is one entry Anything that is not a leaf is not in leafEntries. 67

// Postcondition: ‘ This ’ Huffman object is initialized. // Postcondition: file (identified by s) is dealt with. // Postcondition: priority queue is created from input file. worst case = O(n) 68

// Postcondition: build huffman tree. worst case = constant // Postcondition: create huffman code of each item. // worst case time is constant. // Postcondition: Huffman codes and all data are saved. worst case time = O (n). 69

Fields in the Huffman class Gui priority queue file reader file writer input file name (saved to allow file opening more than once.) Calculate frequency Encode data boolean telling us which file we are reading. 70

71

Method processInput Create priority Q. Build Huffman tree. Create code. save code and the real message into file. 72

Method createPQ Create leafEntries ใ update freq field of each Entry After that, create priority queue using freq. 73

Method createHuffmanTree Loop until the size of priority queue is 1. Create the tree. 74

Method calculateHuffmanCodes Loop on leafEntries For each Entry: There is a variable which is empty string. Look at parent and then fill in the number indicating parent in front of the string, until the root is reached. 75

Example code building Starting with this tree. See next page. 76

Code of f f has its int = = 102, so we set leafEntries[102].code = “ 1010 ” ; Loop is reversing 77

Method saveToFile Loop on leafEntries Send character and its code to a file. Then read the input file Code of input is created and saved into the file. 78

See all the code here 79

Try building a huffman tree from this and reveal the message. 80