I hope that you get along well with your teammate. If not… You can always change. A quick answer about teams.

Slides:



Advertisements
Similar presentations
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.
Advertisements

1 Data Structures and Algorithms Abstract Data Types IV: Heaps and Priority Queues Gal A. Kaminka Computer Science Department.
Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out The “smallest” element.
Quiz3! Midterm! Assignment2! (most) Quiz4! Today’s special: 4 for 1.
1 Heaps & Priority Queues (Walls & Mirrors - Remainder of Chapter 11)
Heapsort.
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.
Heapsort. 2 Why study Heapsort? It is a well-known, traditional sorting algorithm you will be expected to know Heapsort is always O(n log n) Quicksort.
A Binary Tree root leaf. A Binary Tree root leaf descendent of root parent of leaf.
Priority Queues. Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-first-out –The “smallest” element.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
CS 206 Introduction to Computer Science II 02 / 11 / 2009 Instructor: Michael Eckmann.
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,
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
Heapsort Based off slides by: David Matuszek
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Binary search trees. What’s on the menu? ADT DictionaryBST & Algorithms SimulatorComplexity.
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.
Brought to you by Max (ICQ: TEL: ) February 5, 2005 Advanced Data Structures Introduction.
Information and Computer Sciences University of Hawaii, Manoa
Heapsort CSC Why study Heapsort? It is a well-known, traditional sorting algorithm you will be expected to know Heapsort is always O(n log n)
Sorting with Heaps Observation: Removal of the largest item from a heap can be performed in O(log n) time Another observation: Nodes are removed in order.
The Binary Heap. Binary Heap Looks similar to a binary search tree BUT all the values stored in the subtree rooted at a node are greater than or equal.
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.
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.
Starting at Binary Trees
Correction of quizzes. ADTs and implementations Hash tables Graphs.
Data Structure & Algorithm II.  In a multiuser computer system, multiple users submit jobs to run on a single processor.  We assume that the time required.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
CSE 250 September 29 – October 3, A NNOUNCEMENTS Homework 4 due 10/5 Project 1 posted for 10/6 Exam 2 10/8 No classes meet 10/9 Project 1 due 10/26.
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.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
What is a heap? Always keep the thing we are most interested in close to the top (and fast to access). Like a binary search tree, but less structured.
Foundations of Data Structures Practical Session #8 Heaps.
CS 361 – Chapter 5 Priority Queue ADT Heap data structure –Properties –Internal representation –Insertion –Deletion.
Week 13 - Friday.  What did we talk about last time?  Sorting  Insertion sort  Merge sort  Started quicksort.
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 8 : Priority Queue Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
Tree Data Structures. Heaps for searching Search in a heap? Search in a heap? Would have to look at root Would have to look at root If search item smaller.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
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.
Mergeable Heaps David Kauchak cs302 Spring Admin Homework 7?
CS 261 – Fall 2009 Binary Search Trees. Can we do something useful? How can we make a collection using the idea of a binary tree? How about starting with.
Priority Queues, Heaps, and Heapsort CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
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.
CS 367 Introduction to Data Structures Lecture 8.
CSI 312 Dr. Yousef Qawqzeh Heaps and Priority Queue.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
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.
Priority Queues and Heaps. John Edgar  Define the ADT priority queue  Define the partially ordered property  Define a heap  Implement a heap using.
Heap Sort Example Qamar Abbas.
ADT Heap data structure
7/23/2009 Many thanks to David Sun for some of the included slides!
Priority Queue & Heap CSCI 3110 Nan Chen.
Heapsort Heap & Priority Queue.
Instructor: Lilian de Greef Quarter: Summer 2017
Dr. David Matuszek Heapsort Dr. David Matuszek
Heapsort.
Heapsort.
Heapsort.
CO 303 Algorithm Analysis and Design
Heaps.
CMPT 225 Lecture 16 – Heap Sort.
Presentation transcript:

I hope that you get along well with your teammate. If not… You can always change. A quick answer about teams

Implementation of Trees using arrays

Implementation of trees using arrays The structure of a tree in an array Consequences for heap

How to see a binary tree as an array Implementation of trees using arrays ØØ ØØ For a node i, its children are 2i + 1 and 2i + 2.

How to see a binary tree as an array Implementation of trees using arrays Ø57Ø638Ø57Ø For a node i, its children are 2i + 1 and 2i + 2.

Algorithms for a tree in an array Implementation of trees using arrays Let say that a binary search tree is implemented as an array. How would you write the algorithm contains that returns true when a key is in the tree? Ø 2 Ø Ø Ø 3 Ø Ø Ø Ø Ø Ø Ø 4 0 2*0 + 2 = 2 2*2 + 2 = 6 2*6 + 2 = 14 The thing NOT to do would be to just scan the array. Indeed, the array can be very sparse. Worst case: 14 comparisons versus 4.

Algorithms for a tree in an array Implementation of trees using arrays Let say that a binary search tree is implemented as an array. How would you write the algorithm contains that returns true when a key is in the tree? « My momma always said that an array is like a box of chocolates: you don’t have to eat all of them, just pick the ones you like. »

Algorithms for a tree in an array Implementation of trees using arrays Let say that a binary search tree is implemented as an array. How would you write the algorithm contains that returns true when a key is in the tree? For a node i, its children are 2i + 1 and 2i + 2. public boolean contains(int key){ int i = 0; while(i<T.length){ if(T[i]==key) return true; if(key>T[i]) i = 2*i+2; // go right else i = 2*i + 1; // or go left } return false;// did not find it } Time Complexity? Exactly the same that doing it in a pointer-based structure: O(h). ( O(log n) if it’s balanced, O(n) in the worst case… )

Algorithms for a tree in an array Implementation of trees using arrays What about adding in a binary search tree implemented as an array? {1, « I »} {5, « ♥ »} {7, « Mr. French’s »} {8, « labs »} Remember that you always have a key and data bound to it. An array is made of couples {key, data}. public class Couple{ private int key; private Object data; // constructor // setData, getData, getKey When the algorithm does not care about the data, we can neglect it. Otherwise, let’s have a class Couple and our array will be Couple[] T = new Couple[10]; and our array will be:

Algorithms for a tree in an array Implementation of trees using arrays What about adding in a binary search tree implemented as an array? public boolean add(int key, Object o){ if(shortOnSpace()) resize(); int i = 0; while(true){ if(T[i]==null){ T[i] = new Couple(key,o); break; } if(key>T[i].getKey) i = 2*i+2; // go right else i = 2*i + 1; // or go left } if(i>sizeUsed) sizeUsed = i; } We have to resize: when and how much is up to you. Just don’t crash. Assuming we have enough space, we go in the tree as long as we have not inserted the node. Once we have inserted the node, we stop. Since the array may be full of holes, maybe that we did not use more space than before. Otherwise, we have to know up to where we are using the space.

Algorithms for a tree in an array Implementation of trees using arrays Something you’ll like to do for practice: remove an element in a binary search tree implemented with an array.

To make a heap happy, give it an array Implementation of trees using arrays If you use an array, inserting in a heap is like in a LinkedList: insert at the current position, and then go to the next one.

To make a heap happy, give it an array Implementation of trees using arrays If you use an array, inserting in a heap is like in a LinkedList: insert at the current position, and then go to the next one. public boolean add(int key, Object o){ if(index==T.length) resize(); T[index] = new Couple(key, o); index++; } This takes care of the shape: the new node is inserted at the last position. But what about the values? int move = index; while(move!=0 && T[move]>T[Math.floor((move-1)/2)]){ swap(move); // swap move and its father move = Math.floor((move-1)/2); } } After you insert it at the end, swap with the father until the ordering on the keys has been ensured.

To make a heap happy, give it an array Implementation of trees using arrays I insert a task with key 35. The father is in floor[(6-1)/2] = 2. We have 35 > The father is in floor[(2-1)/2] = 0. We have 35 > We are at 0: stop (can’t go any higher)

Heapify Implementation of trees using arrays We have a root of which the left son is a heap, the right son is a heap, but the overall tree is not a heap. Heapify restores the heap property.

Heapify Implementation of trees using arrays We have a root of which the left son is a heap, the right son is a heap, but the overall tree is not a heap. Heapify restores the heap property First, look for the maximum between the root and its two children, and swap. And repeat until there aren’t any more swaps to perform.

Heapify Implementation of trees using arrays Heapify(T): Heapify(T, 0, |T|) Heapify(T, i, n): 2i+1 < n ^ max(T[i], T[2i+1], T[2i+2]) = T[i] → T 2i+1 < n ^ max(T[i], T[2i+1], T[2i+2]) = T[2i+1] → Heapify(T[i↔2i+1], 2i+1, n) 2i+1 < n ^ max(T[i], T[2i+1], T[2i+2]) = T[2i+2] → Heapify(T[i↔2i+2], 2i+2, n) 2i+1 = n ^ T[i] ≥ T[2i+1] → T 2i+1 = n ^ T[i] < T[2i+1] → T[i↔2i+1] 2i+1 > n → T We don’t have to swap: stop and return the array. Find with which son to swap, and continue. At the end: compare with a leaf. If we are a leaf, stop.

removeMax Implementation of trees using arrays The max is always the root. Once you remove it, there will be 1 less element, and we are in an array. You can’t do a shift, because: the structure would be totally messed up it’s in O(n) but we are supposed to optimize removeMax Solution: Replace the root by the last element and call heapify to fix the heap.

removeMax Implementation of trees using arrays Object removeMax(){ Object max = T[0]; T[0] = T[index]; index--; Heapify(T); return max; } Worst case time complexity? Everything is in O(1) and we’re calling Heapify, so it’s the same than the worst case time complexity of Heapify. Heapify works only along one branch, and the tree being balanced a branch is of size O(log n), hence O(log n) time. Similarly, the insertion is in O(log n). GetMax is just looking at the root: O(1).

Happiness Enhancement Program © Implementation of trees using arrays Search for a key in a heap. Write it first if it’s implemented as pointers (Java and specification) and then in an array. Write heapify if the implementation is based on pointers (Java and specification).