6 March 2007 1. Array Implementation of Binary Trees



Similar documents
Cpt S 223. School of EECS, WSU

Binary Heaps. CSE 373 Data Structures

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

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

CS711008Z Algorithm Design and Analysis

Binary Heap Algorithms

Converting a Number from Decimal to Binary

From Last Time: Remove (Delete) Operation

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

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

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

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

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

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)

Exam study sheet for CS2711. List of topics

Analysis of Algorithms I: Binary Search Trees

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

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

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

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

Algorithms and Data Structures

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

Rotation Operation for Binary Search Trees Idea:

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

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

Binary Search Trees 3/20/14

Big Data and Scripting. Part 4: Memory Hierarchies

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

Data Structures Fibonacci Heaps, Amortized Analysis

Why Use Binary Trees?

Algorithms Chapter 12 Binary Search Trees

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

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

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)

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

CS473 - Algorithms I

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

External Memory Geometric Data Structures

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

Chapter 14 The Binary Search Tree

PES Institute of Technology-BSC QUESTION BANK

Full and Complete Binary Trees

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

Sample Questions Csci 1112 A. Bellaachia

TREE BASIC TERMINOLOGIES

Algorithms and Data Structures

Data Structures and Data Manipulation

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:

Ordered Lists and Binary Trees

Data storage Tree indexes

Fundamental Algorithms

Symbol Tables. Introduction

Binary Trees (1) Outline and Required Reading: Binary Trees ( 6.3) Data Structures for Representing Trees ( 6.4)

JAWAA: Easy Web-Based Animation from CS 0 to Advanced CS Courses

- 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

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Binary Trees and Huffman Encoding Binary Search Trees

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

Algorithms and Data Structures Written Exam Proposed SOLUTION

Scalable Prefix Matching for Internet Packet Forwarding

Data Structure [Question Bank]

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

THIS CHAPTER studies several important methods for sorting lists, both contiguous

Binary Search Trees CMPSC 122

Physical Data Organization

EE602 Algorithms GEOMETRIC INTERSECTION CHAPTER 27

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,

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

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

Algorithms. Margaret M. Fleck. 18 October 2010

Analysis of a Search Algorithm

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

APP INVENTOR. Test Review

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

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

Data Structures and Algorithms

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

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

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

Lecture 4: Balanced Binary Search Trees

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

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)

Persistent Binary Search Trees

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

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

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.

Classification/Decision Trees (II)

Cpt S 223. School of EECS, WSU

DATABASE DESIGN - 1DL400

Persistent Data Structures and Planar Point Location

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

Introduction to Data Structures and Algorithms

DESIGN AND ANALYSIS OF ALGORITHMS

A Comparison of Dictionary Implementations

Analysis of Binary Search algorithm and Selection Sort algorithm

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

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

International Journal of Software and Web Sciences (IJSWS)

Transcription:

Heaps CSE 0 Winter 00 March 00 1 Array Implementation of Binary Trees Each node v is stored at index i defined as follows: If v is the root, i = 1 The left child of v is in position i The right child of v is in position i + 1 The parent of v is in position??? 1

Space Analysis of Array Implementation n: number of nodes of binary tree T p M : index of the rightmost leaf of the corresponding full binary tree (or size of the full tree) N: size of the array needed for storing T; N = p M + 1 Best-case scenario: balanced, full binary tree p M = n Worst case scenario: unbalanced tree Height h = n 1 Size of the corresponding full tree: p M = h+1 1= n 1 N = n Space usage: O( n ) 3 Array versus Linked List Linked lists Slower operations due to pointer manipulations Use less space if the tree is unbalanced Rotation (restructuring) code is simple Arrays Faster operations Use less space if the tree is balanced (no pointers) Rotation (restructuring) code is complex

Priority Queues Data structure supporting the following operations: insert (equivalent to enqueue) deletemin (or deletemax) (equivalent to dequeue) Other operations (optional) Applications: Emergency room waiting list Routing priority at routers in a network Printing job scheduling Simple Implementations of PQs Unsorted linked list insertion O( ) deletemin O( ) Sorted linked list insertion O( ) deletemin O( ) Red black trees insertion O( ) deletemin O( ) Unsorted array insertion O( ) deletemin O( ) Sorted array insertion O( ) deletemin O( ) A data structure more efficient for PQs is heaps. 3

Heaps 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 at depth i at depth h, the nodes are filled from left to right The last node of a heap is the rightmost node of depth h Where can we find the smallest key in the heap? The largest key? last node Examples that are not heaps 8

Height of a Heap 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 + + + + h 1 + 1 Thus, n h, i.e., h log n depth 0 1 h 1 h keys 1 h 1 1 Some Notes Given a complete binary tree of height h and size n, h n h+1 1 The definition we just discussed is for a min heap. Analogously, we can declare a max heap if we need to implement deletemax operation instead of deletemin. Which data structure is better for implementing heaps, arrays or linked structure? 10

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 (, Sue) (, Pat) (, Mark) (, Jeff) (, Anna) Insertion into a Heap Method insert 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

Upheap Percolation 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 13 Removal from a Heap Method deletemin 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 1

Downheap Percolation 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 1 Heap Sort Consider a priority queue with n items implemented by means of a heap the space used is O(n) methods insert and deletemin take O(log n) time methods size, isempty, and findmin 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 selectionsort 1 8

Analysis of Heap Sort Stirling s approximation: n! n n e n πn Insertions log1 + log + + log n = log(n!) = O(nlogn) Deletions log1 + log + + log n = log(n!) = O(nlogn) Total = O(nlogn) 1 In-place Heap Sort The heap sort algorithm we just discussed requires a temporary array (the heap). In-place heap sort uses only one array, which is the original array storing the inputs. Needs to build a heap (in-place) from the set of input values buildheap procedure 18

buildheap We can construct a heap storing n given keys in using a bottomup construction with log n phases i 1 i 1 In phase i, pairs of heaps with i 1 keys are merged into heaps with i+1 1 keys i+1 1 1 Example (1) 10 8 1 1 3 0 1 1 3 0 0 10

1 Example () 1 1 0 3 1 1 3 0 Example (3) 1 1 8 3 0 1 1 8 3 0

Example (end) 10 1 8 3 1 0 1 8 3 1 10 0 3 Analysis of buildheap 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

Analysis of buildheap (cont d) Theorem: For the perfect binary tree of height h containing n = h+1 1 nodes, the sum of the heights of all the nodes is h+1 1 (h + 1) buildheap thus runs in O(n) time In-place Heap Sort (Section.) The first step is to build a max heap. Call deletemax to remove the max item (the root). The heap size is reduced by one. The last entry of the heap is now empty. Store the item just removed into that location (copymax). Repeat deletemax and copymax until the heap is empty. Examples: will be shown in class Demo/animation www.cse.iitk.ac.in/users/dsrkg/cs10/applets/sortingii/heapsort/heapsort.html www.hawaii.edu/~copley//hsapplet.html www-cse.uta.edu/~holder/courses/cse30/lectures/applets/sort1/heapsort.html 13

More Heap Operations decreasekey(p, d) increasekey(p, d) delete(p) Demo: http://www.student.seas.gwu.edu/~idsv/idsv.html 1