Algorithms and Data Structures



Similar documents
CS711008Z Algorithm Design and Analysis

Binary Heap Algorithms

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

Binary Heaps. CSE 373 Data Structures

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

From Last Time: Remove (Delete) Operation

6 March Array Implementation of Binary Trees

Converting a Number from Decimal to Binary

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

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

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)

Cpt S 223. School of EECS, WSU

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

Analysis of Algorithms I: Binary Search Trees

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)

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

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

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

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

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

Exam study sheet for CS2711. List of topics

Big Data and Scripting. Part 4: Memory Hierarchies

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

Binary Search Trees CMPSC 122

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

Algorithms Chapter 12 Binary Search Trees

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

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

Algorithm Design and Analysis

Chapter 14 The Binary Search Tree

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Analysis of Binary Search algorithm and Selection Sort algorithm

- 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

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

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,

Union-Find Problem. Using Arrays And Chains

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

Why Use Binary Trees?

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

Binary Search Trees 3/20/14

Binary Trees and Huffman Encoding Binary Search Trees

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

CS473 - Algorithms I

Physical Data Organization

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

Full and Complete Binary Trees

Sample Questions Csci 1112 A. Bellaachia

Cost Model: Work, Span and Parallelism. 1 The RAM model for sequential computation:

Data Structure [Question Bank]

Binary search algorithm

Algorithms and Data Structures

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

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

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

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

Merkle Hash Trees for Distributed Audit Logs

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

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

Loop Invariants and Binary Search

Analysis of Algorithms I: Optimal Binary Search Trees

Symbol Tables. Introduction

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

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

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

CompSci-61B, Data Structures Final Exam

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

The ADT Binary Search Tree

Lecture 1: Course overview, circuits, and formulas

TREE BASIC TERMINOLOGIES

Data storage Tree indexes

Mathematical Induction. Lecture 10-11

Binary Search Trees. Ric Glassey

Lecture 4: Balanced Binary Search Trees

OPTIMAL BINARY SEARCH TREES

International Journal of Software and Web Sciences (IJSWS)

DATA STRUCTURES USING C

UNIVERSITY OF LONDON (University College London) M.Sc. DEGREE 1998 COMPUTER SCIENCE D16: FUNCTIONAL PROGRAMMING. Answer THREE Questions.

Introduction to Algorithms March 10, 2004 Massachusetts Institute of Technology Professors Erik Demaine and Shafi Goldwasser Quiz 1.

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

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

Ordered Lists and Binary Trees

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

Classification/Decision Trees (II)

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

DATABASE DESIGN - 1DL400

Data Structures and Algorithms

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

Data Structure with C

Approximation Algorithms

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

So today we shall continue our discussion on the search engines and web crawlers. (Refer Slide Time: 01:02)

Dynamic programming formulation

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

Data Structures and Algorithms Written Examination

Chapter 13: Query Processing. Basic Steps in Query Processing

SYSM 6304: Risk and Decision Analysis Lecture 5: Methods of Risk Analysis

Binary search tree with SIMD bandwidth optimization using SSE

Transcription:

Algorithms and Data Structures CMPSC 465 LECTURES 20-21 Priority Queues and Binary Heaps Adam Smith S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1

Trees Rooted Tree: collection of nodes and edges Edges go down from root (from parents to children) No two paths to the same node Sometimes, children have names (e.g. left, right, middle, etc) S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 2

Where are trees useful? Some important applications Parse trees (compilers) Heaps Search trees String search Game trees (e.g. chess program) E.g. parse tree for 3*(4+2)*(2^6)*( 8/3) * 3 + ^ / 4 2 2 6 8 3 S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 3

Priority Queue ADT Dynamic set of pairs (key, data), called elements Supports operations: MakeNewPQ() Insert(S,x) where S is a PQ and x is a (key,data) pair Extract-Max(S) removes and returns the element with the highest key value (or one of them if several have the same value) Example: managing jobs on a processor, want to execute job in queue with the highest priority Can also get a min version, that supports Extract-Min instead of Extract-Max Sometimes support additional operations like Delete, Increase-Key, Decrease-Key, etc. S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 4

Heaps: Tree Structure Data Structure that implements Priority Queue Conceptually: binary tree In memory: (often) stored in an array Recall: complete binary tree all leaves at the same level, and every internal node has exactly 2 children Heaps are nearly complete binary trees Every level except possibly the bottom one is full Bottom layer is filled left to right S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 5

Height Heap Height = length of longest simple path from root to some leaf e.g. a one-node heap has height 0, a two- or three-node heap has height 1,... Exercises: What is are max. and min. number of elements in a heap of height h? ans: min = 2 h, max = 2 h+1-1 What is height as a function of number of nodes n? ans: floor( log(n) ) S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 6

Array representation Instead of dynamically allocated tree, heaps often represented in a fixed-size array smaller constants, works well in hardware. Idea: store elements of tree layer by layer, top to bottom, left to right Navigate tree by calculating positions of neighboring nodes: Left(i) := 2i Right(i) := 2i+1 Parent(i) := floor(i/2) Example: [20 15 8 10 7 5 6] S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 7

Review Questions Is the following a valid max-heap? 20 10 4 9 6 3 2 8 7 5 12 1 (If not, repair it to make it valid) Is an array sorted in decreasing order a valid maxheap? S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 8

Local Repair: Heapify Down Two important local repair operations : Heapify Down, Heapify Up Suppose we start from a valid heap and decrease the key of node i, so it is still smaller than parent the two subtrees rooted at i remain valid How do we rearrange nodes to make the heap valid again? Idea: let new, smaller key sink to correct position Find index with largest key among {i, Left(i), Right(i)} If i!= largest, EXCHANGE i with largest and recurse on largest S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 9

Local Repair: Heapify Down Pseudocode in book Running time: O(height) = O(log n) Tight in worst case Correctness: by induction on height S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 10

MAX-HEAPIFY(-DOWN) Exercise: what does Max-Heapify do on the following input? 2.5 10 4 9 6 3 2 8 7 5 0 1 This gives us our first PQ operation: Extract-Max(A) 1. tmp := A[1] 2. A[1] := A[heap-size] 3. heap-size := heap-size-1 4. MAX-HEAPIFY-DOWN(A,1) 5. return tmp S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 11

Local Repair: Heapify Up Two important local repair operations Heapify Down Heapify Up Suppose we start from a valid heap and increase the key of node i, so it is still larger than both children, but might be larger than parent How do we rearrange nodes to make the heap valid again? Idea: let new, larger key float to right position If A[i] > A[Parent(i)], EXCHANGE i with parent and recurse on parent Pseudocode in CLRS Chap 6.2: MAX-HEAPIFY S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 12

Local Repair: Heapify Up Pseudocode in book (see Increase-key ) Running time: O(log n) tight in worst case Correctness: by induction on height S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 13

MAX-HEAPIFY(-UP) Exercise: what does Max-Heapify do on the following input? 20 10 4 9 6 3 2 8 7 21 0 1 This gives us our second PQ operation: Insert(A,x) 1. A[heap-size+1] := x 2. heap-size := heap-size+1 3. MAX-HEAPIFY-UP(A,heap-size) S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 14

Other PQ operations Max(S): return max element without extracting it Increase-Key(S,i,new-key) Decrease-Key(S,i,new-key) Both of these require knowing position of desired element Can be taken care by augmenting using a dictionary data structure, such as hash table Delete(S,i) Delete the element in position i S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 15

Heap Sort Heaps give an easy O(n log n) sorting algorithm: For i=2 to n Insert(A,A[i]) For i= n downto 3 A[i] := Extract-Max(A) There is a faster way (O(n) time) to build a heap from an unsorted array. S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 16

Search Can we search for an element in a heap in sublinear (that is, o(n)) time, in the worst case? How would you prove that such a search algorithm does not exist? S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 17