Chapter 9. Heaps [INA240] Data Structures and Practice Youn-Hee Han

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Transform and Conquer Chapter 6. Transform and Conquer Solve problem by transforming into: a more convenient instance of the same problem (instance simplification)
Trees Types and Operations
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Advanced Data Structures Chapter 16. Priority Queues Collection of elements each of which has a priority. Does not maintain a first-in, first-out discipline.
AA Trees another alternative to AVL trees. Balanced Binary Search Trees A Binary Search Tree (BST) of N nodes is balanced if height is in O(log N) A balanced.
Heapsort By: Steven Huang. What is a Heapsort? Heapsort is a comparison-based sorting algorithm to create a sorted array (or list) Part of the selection.
The Heap ADT In this section of notes you will learn about a new abstract data type, the heap, as well how heaps can be used.
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.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu.
CS 253: Algorithms Chapter 6 Heapsort Appendix B.5 Credit: Dr. George Bebis.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
Analysis of Algorithms CS 477/677
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees,
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
Binary Search Trees Chapter 7 Objectives
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Foundation of Computing Systems Lecture 6 Trees: Part III.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
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.
Data Structures Week 8 Further Data Structures The story so far  Saw some fundamental operations as well as advanced operations on arrays, stacks, and.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu Lecture 9.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
Ceng-112 Data Structures I Figure 9-1 The heap is guaranteed to hold the largest node of the tree in the root. The smaller nodes of a heap can be.
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.
Data Structure II So Pak Yeung Outline Review  Array  Sorted Array  Linked List Binary Search Tree Heap Hash Table.
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.
CS223 Advanced Data Structures and Algorithms 1 Priority Queue and Binary Heap Neil Tang 02/09/2010.
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
Heaps & Priority Queues
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
CIS 068 Welcome to CIS 068 ! Lesson 12: Data Structures 3 Trees.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
1 Heap Sort. A Heap is a Binary Tree Height of tree = longest path from root to leaf =  (lgn) A heap is a binary tree satisfying the heap condition:
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CS 367 Introduction to Data Structures Lecture 8.
Priority Queues and Heaps Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University.
Sept Heapsort What is a heap? Max-heap? Min-heap? Maintenance of Max-heaps -MaxHeapify -BuildMaxHeap Heapsort -Heapsort -Analysis Priority queues.
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.
Binary Search Trees Chapter 7 Objectives
Partially Ordered Data ,Heap,Binary Heap
Heap Chapter 9 Objectives Define and implement heap structures
AA Trees.
Source: Muangsin / Weiss
Heap Chapter 9 Objectives Upon completion you will be able to:
Chapter 8 – Binary Search Tree
B-Tree Insertions, Intro to Heaps
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
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) A heap.
Priority Queues & Heaps
CSE 12 – Basic Data Structures
Chapter 9 The Priority Queue ADT
Priority Queue and Heap
Presentation transcript:

Chapter 9. Heaps [INA240] Data Structures and Practice Youn-Hee Han

1. Basic Concepts Where We Are? TreeBinary Tree Binary Search Tree AVL Search Tree Heap 힙 (Heap): 수북하게 쌓아 올린 더미 Splay Tree

1. Basic Concepts Heap: a binary tree structure with the properties … The tree is complete or nearly complete The key value of each node is greater than or equal to the key value in each of its descendents  Root 의 키가 왼쪽자식과 오른쪽 자식의 키보다 크거나 같다. The subtrees are in turn heaps 주의할 특징 왼쪽 자식과 오른쪽 자식 사이에는 어느 쪽 키가 크던 상관이 없다.

1. Basic Concepts Heap 의 속성 A heap is a special kind of tree. It has two properties that are not generally true for other trees: [Completeness] - The tree is (nearly) complete, which means that nodes are added from top to bottom, left to right, without leaving any spaces. [Heapness] - The item in the tree with the highest priority is at the top of the tree, and the same is true for every subtree. (nearly)

Data Structure5 1. Basic Concepts Max Heap ( 일반적 의미의 Heap) 키 값이 큰 레코드가 우선순위가 높은 것으로 간주 루트노드의 키가 가장 크다. Min Heap Max Heap 과 정 반대 키 값이 작을수록 우선순위가 높다. 예 ] 내신등급

1. Basic Concepts Examples of Heaps Invalid heaps (Why?)

Data Structure7 1. Basic Concepts 정렬 관점에서 … BST 는 약한 의미로 정렬.  왼쪽 자식 키보다 오른쪽 자식 키가 크다. Heap 도 약한 의미로 정렬.  부모의 키가 자식의 키보다 우선 순위가 높다  왼쪽 자식 키와 오른쪽 자식 키는 무관하다. Heap Binary search tree

Data Structure8 2. Maintenance Operations (p. 391) Although Heap is a tree, it is meaningless to traverse it, search it, or print it out. Important operations Insertion Deletion Problem: preserving conditions of max heap 1 st condition: Completeness 2 nd condition: Heapness

Data Structure9 2. Maintenance Operations Inserting a node into heap 1. Insert the node to heap  To preserve 1 st condition, the new node should be added at the last leaf level at the first empty position  2 nd condition could be broken 2. Repair the structure so that 2 nd condition is satisfied  Reheap Up

Data Structure10 2. Maintenance Operations Inserting a node into heap 효율  O(lgN)  삭제보다 비교 횟수가 적음 [ 힙의 삽입 ] “ 신입사원이 오면 일단 말단 자리에 앉힌 다음, 능력껏 위로 진급시키는 것 ( 進級, Reheap Up, Promotion)”

Data Structure11 2. Maintenance Operations Deleting a node from heap 1. Deletion always occurs at the root  To preserve 1 st condition, the last node should move to the root  2 nd condition could be broken 2. Repair the structure so that 2 nd condition is satisfied  Reheap Down [ 힙의 삭제 ] “ 사장자리가 비면 말단 사원을 그 자리에 앉힌 다음, 바로 아래 부하직원보다는 능력이 좋다고 판단될 때까지 강등시키는 것 ( 降等, Reheap Down, Demotion)”

Data Structure12 2. Maintenance Operations Deleting a node from heap 우선순위가 가장 큰 루트노드를 삭제  Completeness 를 유지 하기 위해서는 루트의 삭제와 동시에 마지막 요소를 루트노드 위치로 옮김. Reheap Down  힙 모습의 복원 (Heap Rebuilding)  Reheap !  루트로부터 시작해서 제자리를 찾기까지 굴러 떨어짐  왼쪽, 오른쪽 자식 모두를 비교해서 더 큰 것과 스와핑 (Swaping)

Data Structure13 2. Maintenance Operations Deleting a node from heap 효율  마지막 원소를 루트로 복사하는 데 O(1)  최악의 경우 루트로부터 리프까지 굴러 떨어짐..  비교의 횟수는 총 2lgN 이 된다.  삭제 효율은 O(1) + O(2lgN) ≈ O(lgN)

Data Structure14 2. Maintenance Operations BST vs. Heap 삽입, 삭제, 탐색의 관점에서 Heap 이 BST 보다 더 좋은 구조임.  BST 는 최악의 경우 연결 리스트와 유사  O(N) 의 효율 BST 는 Skewed Binary Tree ( 편향된 이진 트리 ) 가 가능  힙은 완전 (Complete or Nearly Complete) 이진트리로서 균형 트리  균형 트리의 높이는 항상 lg(N) 에 가까움 탐색은 가장 큰 (or 작은 ) 값의 노드를 찾는 작업

Data Structure15 3. Heap Implementation Heap 구현 배열로 표시하는 것이 구현에 매우 효율적  Why? Heap is complete or nearly complete!!!  Parent 와 Child 사이, Siblings 사이에 배열에서의 그 위치에 대한 규칙 형성 배열에 위치하는 순서  루트부터 시작해서 위에서 아래로, 왼쪽에서 오른쪽으로 진행  Root 노드는 항상 배열 인덱스 0.

Data Structure16 3. Heap Implementation Heap 구현 (n: 노드의 총 개수 ) 배열 인덱스 i 에 위치한 노드에 대해서 … LeftChild(i) is at 2i + 1 RightChild(i) is at 2i + 2 Parent(i) is at  (i-1)/2   If i = 0, i is at the root and has no parent.

Data Structure17 3. Heap Implementation Heap 구현 (n: 노드의 총 개수 ) Right Sibling(j) is at j + 1 Left Sibling(k) is at k - 1 The location of the first leaf is at  n/2  The location of the last non-leaf is at  n/2  - 1

Data Structure18 3. Heap Implementation Insert Heap Algorithm insertHeap (heap, last, data) // heap: array of valid heap // last: index to the last node in heap // data: data to be inserted 1. if (heap full) 1. return false 2. end if 3. last++ 4. move data to last node 5. reheapUp (heap, last) 6. Return true

Data Structure19 3. Heap Implementation Reheap Up Algorithm reheapUp (heap, newNode) // heap: array containing an invalid heap // newNode: index location to new data in heap 1. if (newNode is not the root) 1. set parent to parent of newNode 2. if (newNode Key > parent Key) 1. exchange newNode and parent 2. reheapUp (heap, parent) 3. end if 2. end if

Data Structure20 3. Heap Implementation Heap Build Algorithm buildHeap (heap, size) // heap: array containing an invalid heap // size: number of elements in array 1. Set walker to 1 2. loop (walker < size) 1. reheapUp (heap, walker) 2. walker++ 3. end loop Building a heap from unsorted array

Data Structure21 3. Heap Implementation Delete Heap Node Algorithm deleteHeap (heap, last, dataOut) // heap: array of valid heap // last: index to the last node in heap // dataOut: reference for output area 1. if (heap empty) 1. return false 2. end if 3. set dataOut to root data 4. move last data to root 5. reheapDown (heap, 0) 6. Return true

Data Structure22 3. Heap Implementation Reheap Down Algorithm reheapDown (heap, root) // heap: array of data // root: root of heap or subheap 1. if (there is a left subtree) 1. set leftkey to left subtree key 2. if (there is a right subtree) 1. set rightKey to tight subtree key 2. if (leftKey > rightKey) 1. set largeSubtree to left subtree 3. else 1. set largeSubtree to right subtree 3. else 1. set largeSubtree to left subtree 4. if (root key < largeSubtree key) 1. exchange root and largeSubtree 2. reheapDown (heap, largeSubtree) 5. end if 2. end if reheapDown

Data Structure23 4. Heap Application - Selecting K th Element Selecting K th Element in an unsorted list First solution  Sort the list & Select the element at location k Second solution  USE HEAP!!! How to execute the second solution? 1. Heap Creation from an unordered list 크기 순으로 4 번째 엘리먼트는 ?

Data Structure24 How to execute the second solution? 2. delete k – 1 elements from heap 3. place the deleted element at the end of the heap and reduce the heap size by 1 4. After k – 1 elements have been deleted and moved, the top element (index 0 in array) is the k th element 5. reheap to restore the heap so that we are ready for another selection 찾고자 하는 4 번째 엘리먼트 4. Heap Application - Selecting K th Element

Data Structure25 What is Priority Queue? 응급실에서 환자 치료의 예  큐 : 먼저 온 사람을 먼저 치료  스택 : 나중에 온 사람을 먼저 치료  우선순위 큐 (Priority Queue) : 우선순위가 높은 사람 ( 예 : 위급한 사람 ) 을 먼저 치료 Priority Queue 5. Heap Application – Priority Queue an abstract data type supporting the following three operations: - add an element to the queue with an associated priority - Remove and return the element from the queue that has the highest priority - (optionally) peek at the element with highest priority without removing it

Data Structure26 Priority Queue vs. Stack/Queue 시간 : 스택, 큐  스택, 큐에서는 시간에 따라 자료구조를 조직화 시간을 포함한 여러 가지 가치를 우선순위로 가지는 자료구조  우선순위 큐 우선 순위 큐는 각 노드에 “ 우선순위 값 ” 필드가 필요. 우선순위 큐는 스택이나 큐 보다 일반적인 구조 큐나 스택은 우선순위 큐의 특수한 형태로서 시간에 그 우선순위를 부여한 것임 따라서 키 필드가 불필요 5. Heap Application – Priority Queue Priority Queue StackQueue

Data Structure27 Heap is an excellent structure to implement priority queue 5. Heap Application – Priority Queue

Data Structure28 Priority Queue Example An event is represented by  Priority number (1 ~ 5)  Serial number (0 ~ 999) 5. Heap Application – Priority Queue

Data Structure29 Priority Queue Example 5. Heap Application – Priority Queue

Data Structure30 6. Heap Efficiency Heap Efficiency Heap is efficient for extraction of the largest (or smallest) element. Heap is efficient for both insertion and deletion Heap is a compromise of sorted and unsorted structures  Sorted (array or linked-list) structures Very efficient in extraction of largest (smallest) element Inefficient in insertion  Unsorted (array or linked-list) structures Inefficient in extraction of largest (smallest) element Very efficient in insertion

Heap Efficiency RepresentationInsertionDeletion Unordered arrayO(1)O(n) Unordered linked listO(1)O(n) Sorted arrayO(n)O(1) Sorted linked listO(n)O(1) HeapO(log n) 6. Heap Efficiency Data Structure31