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:

Slides:



Advertisements
Similar presentations
Chapter 10: Data Structures II
Advertisements

COL 106 Shweta Agrawal and Amit Kumar
The Dictionary ADT Definition A dictionary is an ordered or unordered list of key-element pairs, where keys are used to locate elements in the list. Example:
Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Priority Queues1 Part-D1 Priority Queues. Priority Queues2 Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is.
Cpt S 223 – Advanced Data Structures Course Review Midterm Exam # 2
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
Heapsort Based off slides by: David Matuszek
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
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.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
9/17/20151 Chapter 12 - Heaps. 9/17/20152 Introduction ► Heaps are largely about priority queues. ► They are an alternative data structure to implementing.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Brought to you by Max (ICQ: TEL: ) February 5, 2005 Advanced Data Structures Introduction.
Chapter 21 Binary Heap.
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.
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
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.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
1 Heaps (Priority Queues) You are given a set of items A[1..N] We want to find only the smallest or largest (highest priority) item quickly. Examples:
HEAPS • Heaps • Properties of Heaps • HeapSort
Chapter 2: Basic Data Structures. Spring 2003CS 3152 Basic Data Structures Stacks Queues Vectors, Linked Lists Trees (Including Balanced Trees) Priority.
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.
© 2006 Pearson Education Chapter 10: Non-linear Data Structures Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
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.
Heapsort. What is a “heap”? Definitions of heap: 1.A large area of memory from which the programmer can allocate blocks as needed, and deallocate them.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
Chapter 13 Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-in-first-out The “smallest”
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.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
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.
CS 367 Introduction to Data Structures Lecture 8.
Priority Queues CS 110: Data Structures and Algorithms First Semester,
Heaps © 2010 Goodrich, Tamassia. Heaps2 Priority Queue ADT  A priority queue (PQ) stores a collection of entries  Typically, an entry is a.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
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.
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.
Sorting Cont. Quick Sort As the name implies quicksort is the fastest known sorting algorithm in practice. Quick-sort is a randomized sorting algorithm.
Heaps, Heap Sort, and Priority Queues. Background: Binary Trees * Has a root at the topmost level * Each node has zero, one or two children * A node that.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Priority Queues and Heaps
Bohyung Han CSE, POSTECH
Chapter 10: Non-linear Data Structures
Heap Chapter 9 Objectives Upon completion you will be able to:
ADT Heap data structure
7/23/2009 Many thanks to David Sun for some of the included slides!
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Priority Queues & Heaps
Priority Queues CSE 373 Data Structures.
Heaps.
Presentation transcript:

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: Words  Their definitions. Social security numbers  People ʼ s names IP addresses  Host names

SimpleMap Java has a sophisticated Map interface, which has an extensive collection of methods and “views”. Here we present a stripped-down version.

Most methods in SimpleMap match the Map API. One exception is keyIterator(), which is equivalent to calling keySet().iterator() in the API.

Implementation using Lists An easy way to implement SimpleMap is to use a List of MapEntry objects, which are key/value pairs.

Put a key into the map Need to check if the key exists. We can use a linear scan.

Put the value of a key Need to check if the key exists. We can use a linear scan.

Remove a key from the map

Check if it contains a given key

Key iterator

Implementation using BST If the keys have a natural ordering, we can represent maps using a BSTSet consisting of MapEntry objects.

Lookup Table Suppose the keys are integers, we could implement a Map by using a look up table, represented as an array of values, indexed by key: The value associated with key K would be stored in the array cell k ::: John Scott Name[ ] = “John Scott” What is the time complexity? Space requirement?

Hash Table 1.For each key use a function, called a hash function, to compute an integer, called they key’s hash code.

Hash Table 2.Take the hash code modulo the array size to get an index into an array. 3.Store the key and the value in a linked list of entries at the array index. Collision: Two different keys may end up with the same hash code, or two different hash codes result in the same array index. Internal data structure?

Java HashCode Every Java Object has a default hashcode() method, which returns a 32-bit integer. For instance, the hashcode () method for the String class (as specified in the Java Standard), looks like this: The two special things about the number 31: It is prime, so that when the user mods out by another number, they have no common factors (unless it's a multiple of 31) It is a Mersenne prime which is a prime number of the form 2n−1. Thus, the product can be done with one shift and one subtract.

Hashing Performance

Hash Maps The standard implementation of hash tables in the Java libraries is called HashMap. The Set version is called HashSet. It is crucial that if two keys are equal, then they must have the same hash code. Thus, if you override equals(), you must also override hashCode().

Rehashing and the Load Factor When more and more elements are added, the table becomes fuller, collisions increase, the bucket lists get longer and longer, and performance deteriorates. Solution: rehash the elements, when n/M exceeds some threshold L (called load factor) Java sets L to be 0.75

Time Complexity

Priority Queue Priority queue: used to prioritize entries. An entry with any key may be inserted at any time, but when peeking or removing, you get the one with the entry whose key is the lowest (or the highest). Applications Event simulations Packet delivery Printer queue Priorities in Highest Priority out

Basic Methods for Priority Queue Add(): Add a new element to the queue peek() : Return the element with the smallest/largest key in the queue remove(): Return and remove the element with the smallest / largest key in the queue

Basic Methods for Priority Queue Add(): Add a new element to the queue peek() : Return the element with the smallest/largest key in the queue remove(): Return and remove the element with the smallest / largest key in the queue

Binary Heaps: An implementation of Priority Queues A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

A binary heap is a complete binary tree whose entries satisfy the “Heap-order property”: No child has a key that is smaller than its parent's key.

A binary heap is a complete binary tree whose entries satisfy the “Heap-order property”: No child has a key that is smaller than its parent's key. Implementation: 1)Using reference-based tree data structure 2)Using an array

Method Implementation E peek(): The heap-order property ensures that the entry with the minimum key is always at the top of the heap. Hence, we simply return the entry at the root node. If the heap is empty, return null or throw an exception.

boolean add(E x) We place the new entry x in the bottom level of the tree, at the first free spot from the left. (If the bottom level is full,start a new level with x at the far left.) In an array- based implementation, we place x in the first free location in the array.

boolean add(E x) We place the new entry x in the bottom level of the tree, at the first free spot from the left. (If the bottom level is full,start a new level with x at the far left.) In an array- based implementation, we place x in the first free location in the array. The problem is, the new entry's key may violate the heap-order property.

Solution: having the entry percolate up the tree until the heap-order property is satisfied: Compare x's key with its parent's key; if x’s key is less, exchange x with its parent, then repeat the procedure with x's new parent.

p ≤ s (where s is x's sibling), p ≤ l, and p ≤ r (where l and r are x's children). We only swap if x < p, which implies that x < s; after the swap, x is the parent of s. After the swap, p is the parent of l and r.

E remove() If the heap is empty, return null or throw an exception. Otherwise, begin by removing the entry at the root node and saving it for the return value. This leaves a hole at the root. We fill the hole with the last entry in the tree, which we call x, so that the tree remains complete. The problem is, it is unlikely that x has the minimum key.

Solution: Percolate x down the heap If x has a child whose key is smaller, swap x with the child having the minimum key. Next, compare x with its new children; if x still violates the heap-order property, again swap x with the child with the minimum key. Continue until x is less than or equal to its children, or reaches a leaf.

Solution: Percolate x down the heap If x has a child whose key is smaller, swap x with the child having the minimum key. Next, compare x with its new children; if x still violates the heap-order property, again swap x with the child with the minimum key. Continue until x is less than or equal to its children, or reaches a leaf.

Performance

Bottom-Up Heap Construction Suppose we are given a bunch of randomly ordered entries, and want to make a heap out of them. We could add() them one by one in O(n log n) time, but there's a faster way. We define one more heap operation.

void heapify() 1.Make a complete tree out of the entries by just throwing them, in any order, into an array. 2.Work backward from the last internal node (non-leaf node) to the root node, in reverse order in the array or the level-order traversal: When visiting a node, percolate its entry down the heap as in remove(). Time complexity?

Heapsort Binary heaps give us yet another O(n log n) sorting algorithm. We use a max heap; i.e., one where the highest- priority item is the one with the largest key, and, thus, this item will be at the root of the heap. A max heap is easily implemented by defining the appropriate comparator. Time complexity?

In-place Sorting We can use the array to both store the heap H and represent the list L. As items are removed, the heap shrinks toward the beginning of the array, making room for the elements removed.