Heaps Goodrich, Tamassia. Heaps 1

Similar documents
6 March Array Implementation of Binary Trees

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

CS711008Z Algorithm Design and Analysis

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

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

Binary Heap Algorithms

Binary Heaps. CSE 373 Data Structures

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)

Cpt S 223. School of EECS, WSU

Exam study sheet for CS2711. List of topics

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

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

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

Converting a Number from Decimal to Binary

Algorithms and Data Structures

From Last Time: Remove (Delete) Operation

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

Binary Search Trees 3/20/14

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

Data Structures Fibonacci Heaps, Amortized Analysis

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

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

Binary Search Trees CMPSC 122

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

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

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

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

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:

Analysis of Algorithms I: Binary Search Trees

Classification/Decision Trees (II)

Full and Complete Binary Trees

Algorithms Chapter 12 Binary Search Trees

Ordered Lists and Binary Trees

Chapter 14 The Binary Search Tree

The ADT Binary Search Tree

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

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

1/1 7/4 2/2 12/7 10/30 12/25

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

Big Data and Scripting. Part 4: Memory Hierarchies

Motivation Suppose we have a database of people We want to gure out who is related to whom Initially, we only have a list of people, and information a

Sample Questions Csci 1112 A. Bellaachia

EE602 Algorithms GEOMETRIC INTERSECTION CHAPTER 27

Algorithms and Data Structures

Fundamental Algorithms

Binary Trees and Huffman Encoding Binary Search Trees

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

Data Structures and Algorithms

Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later).

A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

Outline. Introduction Linear Search. Transpose sequential search Interpolation search Binary search Fibonacci search Other search techniques

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

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

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

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

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

B+ Tree Properties B+ Tree Searching B+ Tree Insertion B+ Tree Deletion Static Hashing Extendable Hashing Questions in pass papers

Tables so far. set() get() delete() BST Average O(lg n) O(lg n) O(lg n) Worst O(n) O(n) O(n) RB Tree Average O(lg n) O(lg n) O(lg n)

MATHEMATICAL ENGINEERING TECHNICAL REPORTS. The Best-fit Heuristic for the Rectangular Strip Packing Problem: An Efficient Implementation

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 221] edge. parent

Symbol Tables. Introduction

External Memory Geometric Data Structures

Closest Pair Problem

Rotation Operation for Binary Search Trees Idea:

DATABASE DESIGN - 1DL400

Data Structure [Question Bank]

Algorithms and Data Structures Written Exam Proposed SOLUTION

External Sorting. Chapter 13. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

A Comparison of Dictionary Implementations

Data Structures and Data Manipulation

APP INVENTOR. Test Review

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

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

TREE BASIC TERMINOLOGIES

External Sorting. Why Sort? 2-Way Sort: Requires 3 Buffers. Chapter 13

Databases and Information Systems 1 Part 3: Storage Structures and Indices

Lecture 4: Balanced Binary Search Trees

An Immediate Approach to Balancing Nodes of Binary Search Trees

Introduction Advantages and Disadvantages Algorithm TIME COMPLEXITY. Splay Tree. Cheruku Ravi Teja. November 14, 2011

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.

Analysis of Algorithms I: Optimal Binary Search Trees

schema binary search tree schema binary search trees data structures and algorithms lecture 7 AVL-trees material

Dynamic 3-sided Planar Range Queries with Expected Doubly Logarithmic Time

Optimal Binary Search Trees Meet Object Oriented Programming

International Journal of Advanced Research in Computer Science and Software Engineering

Classifying Large Data Sets Using SVMs with Hierarchical Clusters. Presented by :Limou Wang

Binary Search Trees. Ric Glassey

International Journal of Software and Web Sciences (IJSWS)

ER E P M A S S I CONSTRUCTING A BINARY TREE EFFICIENTLYFROM ITS TRAVERSALS DEPARTMENT OF COMPUTER SCIENCE UNIVERSITY OF TAMPERE REPORT A

Persistent Binary Search Trees

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

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Algorithms. Margaret M. Fleck. 18 October 2010

Binary Search Trees (BST)

PES Institute of Technology-BSC QUESTION BANK

Analysis of Binary Search algorithm and Selection Sort algorithm

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Chapter 13: Query Processing. Basic Steps in Query Processing

Euclidean Minimum Spanning Trees Based on Well Separated Pair Decompositions Chaojun Li. Advised by: Dave Mount. May 22, 2014

Binary Coded Web Access Pattern Tree in Education Domain

Transcription:

Heaps Heaps 1

Recall Priority Queue ADT (.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue ADT insert(k, x) inserts an entry with key k and value x removemin() removes and returns the entry with smallest key Additional methods min() returns, but does not remove, an entry with smallest key size(), isempty() Applications: Standby flyers Auctions Stock market Heaps

Recall Priority Queue Sorting (.1.4) We can use a priority queue to sort a set of comparable elements Insert the elements with a series of insert operations Remove the elements in sorted order with a series of removemin operations The running time depends on the priority queue implementation: Unsorted sequence gives selection-sort: O(n ) time Sorted sequence gives insertion-sort: O(n ) time Can we do better? Algorithm PQ-Sort(S, C) Input sequence S, comparator C for the elements of S Output sequence S sorted in increasing order according to C P priority queue with comparator C while S.isEmpty () e S.remove (S. first ()) P.insertItem(e, e) while P.isEmpty() e P.removeMin() S.insertLast(e) Heaps 3

Heaps (.3) A heap is a binary tree storing keys at its nodes and satisfying the following properties: Heap-Order: for every internal node v other than the root, key(v) key(parent(v)) Complete Binary Tree: let h be the height of the heap for i = 0,, h 1, there are i nodes of depth i at depth h 1, the internal nodes are to the left of the external nodes The last node of a heap is the rightmost node of depth h last node Heaps 4

Height of a Heap (.3.1) Theorem: A heap storing n keys has height O(log n) Proof: (we apply the complete binary tree property) Let h be the height of a heap storing n keys Since there are i keys at depth i = 0,, h 1 and at least one key at depth h, we have n 1 + + 4 + + h 1 + 1 Thus, n h, i.e., h log n depth 0 1 h 1 h keys 1 h 1 1 Heaps

Heaps and Priority Queues We can use a heap to implement a priority queue We store a (key, element) item at each internal node We keep track of the position of the last node For simplicity, we show only the keys in the pictures (, Sue) (, Pat) (, Mark) (, Jeff) (, Anna) Heaps

Insertion into a Heap (.3.3) Method insertitem of the priority queue ADT corresponds to the insertion of a key k to the heap The insertion algorithm consists of three steps Find the insertion node z (the new last node) Store k at z Restore the heap-order property (discussed next) 1 z insertion node z Heaps

Upheap After the insertion of a new key k, the heap-order property may be violated Algorithm upheap restores the heap-order property by swapping k along an upward path from the insertion node Upheap terminates when the key k reaches the root or a node whose parent has a key smaller than or equal to k Since a heap has height O(log n), upheap runs in O(log n) time 1 z 1 z Heaps 8

Removal from a Heap (.3.3) Method removemin of the priority queue ADT corresponds to the removal of the root key from the heap The removal algorithm consists of three steps Replace the root key with the key of the last node w Remove w Restore the heap-order property (discussed next) w w last node new last node Heaps

Downheap After replacing the root key with the key k of the last node, the heap-order property may be violated Algorithm downheap restores the heap-order property by swapping key k along a downward path from the root Upheap terminates when key k reaches a leaf or a node whose children have keys greater than or equal to k Since a heap has height O(log n), downheap runs in O(log n) time w w Heaps 10

Updating the Last Node The insertion node can be found by traversing a path of O(log n) nodes Go up until a left child or the root is reached If a left child is reached, go to the right child Go down left until a leaf is reached Similar algorithm for updating the last node after a removal Heaps 11

Heap-Sort (.4.4) Consider a priority queue with n items implemented by means of a heap the space used is O(n) methods insert and removemin take O(log n) time methods size, isempty, and min take time O(1) time Using a heap-based priority queue, we can sort a sequence of n elements in O(n log n) time The resulting algorithm is called heap-sort Heap-sort is much faster than quadratic sorting algorithms, such as insertion-sort and selection-sort Heaps 1

Vector-based Heap Implementation (.4.3) We can represent a heap with n keys by means of a vector of length n + 1 For the node at rank i the left child is at rank i the right child is at rank i + 1 Links between nodes are not explicitly stored The cell of at rank 0 is not used Operation insert corresponds to inserting at rank n + 1 Operation removemin corresponds to removing at rank n Yields in-place heap-sort 0 1 3 4 Heaps 13

Merging Two Heaps We are given two two heaps and a key k 8 3 4 We create a new heap with the root node storing k and with the two heaps as subtrees We perform downheap to restore the heaporder property 8 3 3 4 4 8 Heaps 14

Bottom-up Heap Construction (.4.3) We can construct a heap storing n given keys in using a bottom-up construction with log n phases In phase i, pairs of heaps with i 1 keys are merged into heaps with i+1 1 keys i 1 i 1 i+1 1 Heaps 1

Example 1 1 4 1 3 0 11 1 1 4 1 3 0 Heaps 1

Example (contd.) 11 1 1 4 1 3 0 1 4 3 1 1 11 0 Heaps 1

Example (contd.) 8 1 4 3 1 1 11 0 4 1 8 3 1 1 11 0 Heaps 18

Example (end) 10 4 1 8 3 1 1 11 0 4 1 8 3 1 10 1 11 0 Heaps 1

Analysis We visualize the worst-case time of a downheap with a proxy path that goes first right and then repeatedly goes left until the bottom of the heap (this path may differ from the actual downheap path) Since each node is traversed by at most two proxy paths, the total number of nodes of the proxy paths is O(n) Thus, bottom-up heap construction runs in O(n) time Bottom-up heap construction is faster than n successive insertions and speeds up the first phase of heap-sort Heaps 0