SlideShare a Scribd company logo
1 of 41
Download to read offline
Chapter 8 - Heaps
 Binary Heap. Min-heap. Max-heap.
 Efficient implementation of heap ADT: use of array
 Basic heap algorithms: ReheapUp, ReheapDown, Insert Heap,
Delete Heap, Built Heap
 d-heaps
 Heap Applications:
 Select Algorithm
 Priority Queues
 Heap sort
 Advanced implementations of heaps: use of pointers
 Leftist heap
 Skew heap
 Binomial queues 1
Binary Heaps
DEFINITION: A max-heap is a binary tree
structure with the following properties:
• The tree is complete or nearly complete.
• The key value of each node is greater than
or equal to the key value
2
DEFINITION: A min-heap is a binary tree
structure with the following properties:
• The tree is complete or nearly complete.
• The key value of each node is less than or
equal to the key value in each of its
descendents.
all<=K all<=K
K
all>=K all>=K
K
max-heap
min-heap
Properties of Binary Heaps
 Structure property of heaps
 Key value order of heaps
3
Properties of Binary Heaps
Structure property of heaps:
• A complete or nearly complete binary tree.
• If the height is h, the number of nodes n is between
2h-1 and (2h -1)
• Complete tree: n = 2h -1 when last level is full.
• Nearly complete: All nodes in the last level are on the left.
• h = |log2 n| + 1
• Can be represented in an array and no pointers are necessary.
4
Properties of Binary Heaps
Key value order of max-heap:
(max-heap is often called as heap)
5
Basic heap algorithms
ReheapUp: repairs a "broken" heap by floating the last
element up the tree until it is in its correct location.
6
Basic heap algorithms
ReheapDown: repairs a "broken" heap by pushing the root of
the subtree down until it is in its correct location.
7
Contiguous Implementation of Heaps
0 1 2 3 4 5 6
A B C D E F G ...
8
Conceptual
Physical
Heap
data <Array of <DataType> >
count <int> //number of elements in heap
End Heap
2i+1 2i+2
i
|(i-1)/2|
ReheapUp
Algorithm ReheapUp (val position <int>)
Reestablishes heap by moving data in position up to its correct location.
Pre All data in the heap above this position satisfy key value order of a heap,
except the data in position.
Post Data in position has been moved up to its correct location.
Uses Recursive function ReheapUp.
1. if (position <> 0) // the parent of position exists.
1. parent = (position-1)/2
2. if (data[position].key > data[parent].key)
1. swap(position, parent) // swap data at position with data at parent.
2. ReheapUp(parent)
2. return
End ReheapUp
9
ReheapDown
Algorithm ReheapDown (val position <int>, val lastPosition <int>)
Reestablishes heap by moving data in position down to its correct location.
Pre All data in the subtree of position satisfy key value order of a heap, except the
data in position.
Post Data in position has been moved down to its correct location.
Uses Recursive function ReheapDown.
1. leftChild = position *2 + 1
2. rightChild = position *2 + 2
3. if ( leftChild <= lastPosition ) // the left child of position exists.
1. if ( rightChild <= lastPosition) AND ( data[rightChild].key > data[leftChild].key )
1. child = rightChild
2. else
1. child = leftChild // choose larger child to compare with data in position
3. if ( data[child].key > data[position].key )
1. swap(child, position) // swap data at position with data at child.
2. ReheapDown(child, lastPosition)
4. return
10
Insert new element into min-heap
The new element is put to the last position, and ReheapUp is called for
that position. 11
Insert 14:
14
14
14
<ErrorCode> InsertHeap (val DataIn <DataType>) // Recursive version.
Inserts new data into the min-heap.
Post DataIn has been inserted into the heap and the heap order property
is maintained.
Return overflow or success
Uses recursive function ReheapUp.
1. if (heap is full)
1. return overflow
2. else
1. data[count ] = DataIn
2. ReheapUp(count )
3. count = count + 1
4. return success
End InsertHeap
12
<ErrorCode> InsertHeap (val DataIn <DataType>) // Iterative version
Inserts new data into the min-heap.
Post DataIn has been inserted into the heap and the heap order property
is maintained.
Return overflow or success
1. if (heap is full)
1. return overflow
2. else
1. current_position = count - 1
2. loop (the parent of the element at the current_position is exists) AND
(parent.key > DataIn .key)
1. data[current_position] = parent
2. current_position = position of parent
3. data[current_position] = DataIn
4. count = count + 1
5. return success
End InsertHeap 13
Delete minimum element from min-heap
14
The element in the last position is put to the position of the root, and
ReheapDown is called for that position.
31
31
31
31
Delete minimum element from min-heap
15
The element in the last position is put to the position of the root, and
ReheapDown is called for that position.
31
<ErrorCode> DeleteHeap (ref MinData <DataType>) // Recursive version
Removes the minimum element from the min-heap.
Post MinData receives the minimum data in the heap and this data
has been removed. The heap has been rearranged.
Return underflow or success
Uses recursive function ReheapDown.
1. if (heap is empty)
1. return underflow
2. else
1. MinData = Data[0]
2. Data[0] = Data[count -1]
3. count = count - 1
4. ReheapDown(0, count -1)
5. return success
End DeleteHeap
16
<ErrorCode> DeleteHeap (ref MinData <DataType>) // Iterative version
Removes the minimum element from the min-heap.
Post MinData receives the minimum data in the heap and this data
has been removed. The heap has been rearranged.
Return underflow or success
1. if (heap is empty)
1. return underflow
2. else
1. MinData = Data[0]
2. lastElement = Data[count – 1] // The number of elements in the
// heap is decreased so the last
// element must be moved
// somewhere in the heap.
17
// DeleteHeap(cont.) // Iterative version
3. current_position = 0
4. continue = TRUE
5. loop (the element at the current_position has children) AND
(continue = TRUE)
1. Let child is the smaller of two children
2. if (lastElement.key > child.key )
1. Data[current_position] = child
2. current_position = current_position of child
3. else
1. continue = FALSE
6. Data[current_position] = lastElement
7. count = count - 1
8. return success
End DeleteHeap
18
Build heap
<ErrorCode> BuildHeap (val listOfData <List>)
Builds a heap from data from listOfData.
Pre listOfData contains data need to be inserted into an empty heap.
Post Heap has been built.
Return overflow or success
Uses Recursive function ReheapUp.
1. count = 0
2. loop (heap is not full) AND (more data in listOfData)
1. listOfData.Retrieve(count, newData)
2. data[count] = newData
3. ReheapUp( count)
4. count = count + 1
3. if (count < listOfData.Size() )
1. return overflow
4. else
1. return success
End BuildHeap 19
Build heap
Algorithm BuildHeap2 ()
Builds a heap from an array of random data.
Pre Array of count random data.
Post Array of data becames a heap.
Uses Recursive function ReheapDown.
1. position = count / 2 -1
2. loop (position >=0)
1. ReheapDown(position, count-1)
2. position = position - 1
3. return
End BuildHeap2
20
Complexity of Binary Heap Operations
21
d-heaps
 d-heap is a simple generalization of a binary heap.
 In d-heap, all nodes have d children.
 d-heap improve the running time of InsertElement to O(logdn).
 For large d, DeleteMin operation is more expensive: the minimum of
d children must be found, which takes d-1 comparisons.
 The multiplications and divisions to find children and parents are
now by d, which increases the running time. (If d=2, use of the bit
shift is faster).
 d-heap is suitable for the applications where the number of Insertion
is greater than the number of DeleteMin.
22
Heap Applications
Select Algorithms.
Priority Queues.
Heap sort (we will see in the Sorting Chapter).
23
Select Algorithms
Determine the kth largest element in an unsorted list
Algorithm 1a:
• Read the elements into an array, sort them.
• Return the appropriate element.
The running time of a simple sorting algorithm is O(n2)
24
Select Algorithms
Determine the kth largest element in an unsorted list
Algorithm 1b:
• Read k elements into an array, sort them.
• The smallest of these is in the kth position.
• Process the remaining elements one by one.
• Compare the coming element with the kth element in
the array.
• If the coming element is large, the kth element is
removed, the new element is placed in the correct
place.
The running time is O(n2) 25
Select Algorithms
Determine the kth largest element in an unsorted list
Algorithm 2a:
• Build a max-heap.
• Detele k-1 elements from the heap.
• The desired element will be at the top.
The running time is O(nlog2n)
26
Select Algorithms
Determine the kth largest element in an unsorted list
Algorithm 2b:
• Build a min-heap of k elements.
• Process the remaining elements one by one.
• Compare the coming element with the minimum
element in the heap (the element on the root of heap).
• If the coming element is large, the minimum element is
removed, the new element is placed in the correct place
(reheapdown).
The running time is O(nlog2n)
27
Priority Queue ADT
• Jobs are generally placed on a queue to wait for the services.
• In the multiuser environment, the operating system scheduler must
decide which of several processes to run.
• Short jobs finish as fast as possible, so they should have precedence
over other jobs.
• Otherwise, some jobs are still very important and should also have
precedence.
These applications require a special kind of queue: a priority queue.
28
Priority Queue ADT
DEFINITION of Priority Queue ADT:
Elements are enqueued accordingly to their priorities.
Minimum element is dequeued first.
Basic Operations:
• Create
• InsertElement: Inserts new data to the position accordingly to its
priority order in queue.
• DeleteMin: Removes the data with highest priority order.
• RetrieveMin: Retrieves the data with highest priority order.
29
• Each element has a priority to be dequeued.
• Minimum value of key has highest priority order.
Priority Queue ADT
Extended Operations:
• Clear
• isEmpty
• isFull
• RetrieveMax: Retrieves the data with lowest priority
order.
• IncreasePriority Changes the priority of some data
• DecreasePriority which has been inserted in queue.
• DeleteElement: Removes some data out of the queue.
30
Specifications for Priority Queue ADT
<ErrorCode> InsertElement (val DataIn <DataType>)
<ErrorCode> DeleteMin (ref MinData <DataType>)
<ErrorCode> RetrieveMin (ref MinData <DataType>)
<ErrorCode> RetrieveMax (ref MaxData <DataType>)
<ErrorCode> IncreasePriority (val position <int>,
val PriorityDelta <KeyType>)
<ErrorCode> DecreasePriority (val position <int>,
val PriorityDelta <KeyType>)
<ErrorCode> DeleteElement (val position <int>,
ref DataOut <DataType>)
<bool> isEmpty()
<bool> isFull()
<void> clear() 31
Implementations of Priority Queue
 Use linked list:
 Simple linked list:
• Insertion performs at the front, requires O(1).
• DeleteMin requires O(n) for searching of the minimum data.
 Sorted linked list:
• Insertion requires O(n) for searching of the appropriate
position.
• DeleteMin requires O(1).
32
Implementations of Priority Queue
 Use BST:
• Insertion requires O(log2 n).
• DeleteMin requires O(log2 n).
• But DeleteMin , repeatedly removing node in the left subtree,
seem to hurt balance of the tree.
33
Implementations of Priority Queue
 Use min-heap:
• Insertion requires O(log2 n).
• DeleteMin requires O(log2 n).
34
Insert and Remove element into/from
priority queue
<ErrorCode> InsertElement (val DataIn <DataType>):
InsertHeap Algorithm
<ErrorCode> DeleteMin (ref MinData <DataType>):
DeleteHeap Algorithm
35
Retrieve minimum element in priority queue
<ErrorCode> RetrieveMin (ref MinData <DataType>)
Retrieves the minimum element in the heap.
Post MinData receives the minimum data in the heap and the heap
remains unchanged.
Return underflow or success
1. if (heap is empty)
1. return underflow
2. else
1. MinData = Data[0]
2. return success
End RetrieveMin 36
Retrieve maximum element in priority queue
<ErrorCode> RetrieveMax (ref MaxData <DataType>)
Retrieves the maximum element in the heap.
Post MaxData receives the maximum data in the heap and the heap
remains unchanged.
Return underflow or success
1. if (heap is empty)
1. return underflow
2. else
1. Sequential search the maximum data in the right half elements
of the heap (the leaves of the heap). The first leaf is at the
position count/2.
2. return success
End RetrieveMax 37
Change the priority of an element in
priority queue
<ErrorCode> IncreasePriority (val position <int>,
val PriorityDelta <KeyType>)
Increases priority of an element in the heap.
Post Element at position has its priority increased by PriorityDelta
and has been moved to correct position.
Return rangeError or success
Uses ReheapDown.
38
Change the priority of an element in
priority queue
<ErrorCode> DecreasePriority (val position <int>,
val PriorityDelta <KeyType>)
Decreases priority of an element in the heap.
Post Element at position has its priority decreased by PriorityDelta
and has been moved to correct position.
Return rangeError or success
Uses ReheapUp.
39
Remove an element out of priority queue
<ErrorCode> DeleteElement (val position <int>,
ref DataOut <DataType>)
Removes an element out of the min-heap.
Post DataOut contains data in the element at position, this element
has been removed. The heap has been rearranged.
Return rangeError or success
1. if (position>=count ) OR (position <0)
1. return rangeError
2. else
1. DataOut = Data[position]
2. DecreasePriority(position, VERY_LARGE_VALUE),
3. DeleteMin(MinData)
4. return success
End DeleteElement 40
Advanced implementations of heaps
 Advanced implementations of heaps: use of pointers
 Leftist heap
 Skew heap
 Binomial queues
Use of pointers allows the merge operations (combine two heaps
into one) to perform easily.
41

More Related Content

What's hot

Heap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmHeap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmLearning Courses Online
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort AlgorithmLemia Algmri
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxAlbin562191
 
Data Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesData Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesManishPrajapati78
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sortMadhu Bala
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]Muhammad Hammad Waseem
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Muhammad Hammad Waseem
 

What's hot (20)

Heap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmHeap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap Algorithm
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Heap sort
Heap sortHeap sort
Heap sort
 
Heap tree
Heap treeHeap tree
Heap tree
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptx
 
Heap tree
Heap treeHeap tree
Heap tree
 
Data Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and TreesData Structure and Algorithms Heaps and Trees
Data Structure and Algorithms Heaps and Trees
 
Heapsort ppt
Heapsort pptHeapsort ppt
Heapsort ppt
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
Heap sort
Heap sortHeap sort
Heap sort
 
Splay Tree
Splay TreeSplay Tree
Splay Tree
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
Expression trees
Expression treesExpression trees
Expression trees
 
Hash table
Hash tableHash table
Hash table
 
Heap
HeapHeap
Heap
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
b+ tree
b+ treeb+ tree
b+ tree
 
Bloom filters
Bloom filtersBloom filters
Bloom filters
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 

Viewers also liked

Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6chidabdu
 
Exploiting Memory Overflows
Exploiting Memory OverflowsExploiting Memory Overflows
Exploiting Memory OverflowsAnkur Tyagi
 
How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012_mr_me
 
Final lfh presentation (3)
Final lfh presentation (3)Final lfh presentation (3)
Final lfh presentation (3)__x86
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)swajahatr
 
D2 t2 steven seeley - ghost in the windows 7 allocator
D2 t2   steven seeley - ghost in the windows 7 allocatorD2 t2   steven seeley - ghost in the windows 7 allocator
D2 t2 steven seeley - ghost in the windows 7 allocator_mr_me
 
How Safe is your Link ?
How Safe is your Link ?How Safe is your Link ?
How Safe is your Link ?Peter Hlavaty
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMMikhail Egorov
 
CNIT 127 Ch 5: Introduction to heap overflows
CNIT 127 Ch 5: Introduction to heap overflowsCNIT 127 Ch 5: Introduction to heap overflows
CNIT 127 Ch 5: Introduction to heap overflowsSam Bowne
 
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesWindows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesPeter Hlavaty
 
Expanding the control over the operating system from the database
Expanding the control over the operating system from the databaseExpanding the control over the operating system from the database
Expanding the control over the operating system from the databaseBernardo Damele A. G.
 

Viewers also liked (20)

Heapsort
HeapsortHeapsort
Heapsort
 
Heap property
Heap propertyHeap property
Heap property
 
HeapSort
HeapSortHeapSort
HeapSort
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
 
Exploiting Memory Overflows
Exploiting Memory OverflowsExploiting Memory Overflows
Exploiting Memory Overflows
 
Heapsort
HeapsortHeapsort
Heapsort
 
How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012
 
Final lfh presentation (3)
Final lfh presentation (3)Final lfh presentation (3)
Final lfh presentation (3)
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
 
D2 t2 steven seeley - ghost in the windows 7 allocator
D2 t2   steven seeley - ghost in the windows 7 allocatorD2 t2   steven seeley - ghost in the windows 7 allocator
D2 t2 steven seeley - ghost in the windows 7 allocator
 
Heaps
HeapsHeaps
Heaps
 
How Safe is your Link ?
How Safe is your Link ?How Safe is your Link ?
How Safe is your Link ?
 
Heapify
HeapifyHeapify
Heapify
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORM
 
chapter - 6.ppt
chapter - 6.pptchapter - 6.ppt
chapter - 6.ppt
 
CNIT 127 Ch 5: Introduction to heap overflows
CNIT 127 Ch 5: Introduction to heap overflowsCNIT 127 Ch 5: Introduction to heap overflows
CNIT 127 Ch 5: Introduction to heap overflows
 
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesWindows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
 
Expanding the control over the operating system from the database
Expanding the control over the operating system from the databaseExpanding the control over the operating system from the database
Expanding the control over the operating system from the database
 
ORM Injection
ORM InjectionORM Injection
ORM Injection
 
Linked list
Linked listLinked list
Linked list
 

Similar to Binary Heaps and Applications

Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfComplete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfamericanopticalscbe
 
Heap Sort 1053.pptx
Heap Sort 1053.pptxHeap Sort 1053.pptx
Heap Sort 1053.pptxZainiXh
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithmsmultimedia9
 
Heap Hand note
Heap Hand noteHeap Hand note
Heap Hand noteAbdur Rouf
 
Binary heap (Priority Queue).ppt
Binary heap (Priority Queue).pptBinary heap (Priority Queue).ppt
Binary heap (Priority Queue).pptMano Arun
 
Stacks
StacksStacks
StacksAcad
 
USING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdfUSING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdflohithkart
 
Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfarihantstoneart
 
Ds
DsDs
DsAcad
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxssuser454af01
 
For problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfFor problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfanjandavid
 

Similar to Binary Heaps and Applications (20)

Heap Tree.pdf
Heap Tree.pdfHeap Tree.pdf
Heap Tree.pdf
 
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfComplete the classes shown below 1. The MinHeap Class Write necessa.pdf
Complete the classes shown below 1. The MinHeap Class Write necessa.pdf
 
Priority queue
Priority queuePriority queue
Priority queue
 
Heap Sort 1053.pptx
Heap Sort 1053.pptxHeap Sort 1053.pptx
Heap Sort 1053.pptx
 
4 heapsort pq
4 heapsort pq4 heapsort pq
4 heapsort pq
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Heap Hand note
Heap Hand noteHeap Hand note
Heap Hand note
 
Heap, quick and merge sort
Heap, quick and merge sortHeap, quick and merge sort
Heap, quick and merge sort
 
Binary heap (Priority Queue).ppt
Binary heap (Priority Queue).pptBinary heap (Priority Queue).ppt
Binary heap (Priority Queue).ppt
 
Stacks
StacksStacks
Stacks
 
Ch15 Heap
Ch15 HeapCh15 Heap
Ch15 Heap
 
USING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdfUSING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdf
 
Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdf
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Leftlist Heap-1.pdf
Leftlist Heap-1.pdfLeftlist Heap-1.pdf
Leftlist Heap-1.pdf
 
Ds
DsDs
Ds
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
 
C07.heaps
C07.heapsC07.heaps
C07.heaps
 
For problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfFor problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdf
 

More from Hoang Nguyen

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your siteHoang Nguyen
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest apiHoang Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsHoang Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksHoang Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheHoang Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceHoang Nguyen
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friendHoang Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in pythonHoang Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonHoang Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonHoang Nguyen
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisHoang Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 

More from Hoang Nguyen (20)

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
 
Api crash
Api crashApi crash
Api crash
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Cache recap
Cache recapCache recap
Cache recap
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python basics
Python basicsPython basics
Python basics
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Learning python
Learning pythonLearning python
Learning python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Object model
Object modelObject model
Object model
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

Binary Heaps and Applications

  • 1. Chapter 8 - Heaps  Binary Heap. Min-heap. Max-heap.  Efficient implementation of heap ADT: use of array  Basic heap algorithms: ReheapUp, ReheapDown, Insert Heap, Delete Heap, Built Heap  d-heaps  Heap Applications:  Select Algorithm  Priority Queues  Heap sort  Advanced implementations of heaps: use of pointers  Leftist heap  Skew heap  Binomial queues 1
  • 2. Binary Heaps DEFINITION: A max-heap is a binary tree structure with the following properties: • The tree is complete or nearly complete. • The key value of each node is greater than or equal to the key value 2 DEFINITION: A min-heap is a binary tree structure with the following properties: • The tree is complete or nearly complete. • The key value of each node is less than or equal to the key value in each of its descendents. all<=K all<=K K all>=K all>=K K max-heap min-heap
  • 3. Properties of Binary Heaps  Structure property of heaps  Key value order of heaps 3
  • 4. Properties of Binary Heaps Structure property of heaps: • A complete or nearly complete binary tree. • If the height is h, the number of nodes n is between 2h-1 and (2h -1) • Complete tree: n = 2h -1 when last level is full. • Nearly complete: All nodes in the last level are on the left. • h = |log2 n| + 1 • Can be represented in an array and no pointers are necessary. 4
  • 5. Properties of Binary Heaps Key value order of max-heap: (max-heap is often called as heap) 5
  • 6. Basic heap algorithms ReheapUp: repairs a "broken" heap by floating the last element up the tree until it is in its correct location. 6
  • 7. Basic heap algorithms ReheapDown: repairs a "broken" heap by pushing the root of the subtree down until it is in its correct location. 7
  • 8. Contiguous Implementation of Heaps 0 1 2 3 4 5 6 A B C D E F G ... 8 Conceptual Physical Heap data <Array of <DataType> > count <int> //number of elements in heap End Heap 2i+1 2i+2 i |(i-1)/2|
  • 9. ReheapUp Algorithm ReheapUp (val position <int>) Reestablishes heap by moving data in position up to its correct location. Pre All data in the heap above this position satisfy key value order of a heap, except the data in position. Post Data in position has been moved up to its correct location. Uses Recursive function ReheapUp. 1. if (position <> 0) // the parent of position exists. 1. parent = (position-1)/2 2. if (data[position].key > data[parent].key) 1. swap(position, parent) // swap data at position with data at parent. 2. ReheapUp(parent) 2. return End ReheapUp 9
  • 10. ReheapDown Algorithm ReheapDown (val position <int>, val lastPosition <int>) Reestablishes heap by moving data in position down to its correct location. Pre All data in the subtree of position satisfy key value order of a heap, except the data in position. Post Data in position has been moved down to its correct location. Uses Recursive function ReheapDown. 1. leftChild = position *2 + 1 2. rightChild = position *2 + 2 3. if ( leftChild <= lastPosition ) // the left child of position exists. 1. if ( rightChild <= lastPosition) AND ( data[rightChild].key > data[leftChild].key ) 1. child = rightChild 2. else 1. child = leftChild // choose larger child to compare with data in position 3. if ( data[child].key > data[position].key ) 1. swap(child, position) // swap data at position with data at child. 2. ReheapDown(child, lastPosition) 4. return 10
  • 11. Insert new element into min-heap The new element is put to the last position, and ReheapUp is called for that position. 11 Insert 14: 14 14 14
  • 12. <ErrorCode> InsertHeap (val DataIn <DataType>) // Recursive version. Inserts new data into the min-heap. Post DataIn has been inserted into the heap and the heap order property is maintained. Return overflow or success Uses recursive function ReheapUp. 1. if (heap is full) 1. return overflow 2. else 1. data[count ] = DataIn 2. ReheapUp(count ) 3. count = count + 1 4. return success End InsertHeap 12
  • 13. <ErrorCode> InsertHeap (val DataIn <DataType>) // Iterative version Inserts new data into the min-heap. Post DataIn has been inserted into the heap and the heap order property is maintained. Return overflow or success 1. if (heap is full) 1. return overflow 2. else 1. current_position = count - 1 2. loop (the parent of the element at the current_position is exists) AND (parent.key > DataIn .key) 1. data[current_position] = parent 2. current_position = position of parent 3. data[current_position] = DataIn 4. count = count + 1 5. return success End InsertHeap 13
  • 14. Delete minimum element from min-heap 14 The element in the last position is put to the position of the root, and ReheapDown is called for that position. 31 31 31 31
  • 15. Delete minimum element from min-heap 15 The element in the last position is put to the position of the root, and ReheapDown is called for that position. 31
  • 16. <ErrorCode> DeleteHeap (ref MinData <DataType>) // Recursive version Removes the minimum element from the min-heap. Post MinData receives the minimum data in the heap and this data has been removed. The heap has been rearranged. Return underflow or success Uses recursive function ReheapDown. 1. if (heap is empty) 1. return underflow 2. else 1. MinData = Data[0] 2. Data[0] = Data[count -1] 3. count = count - 1 4. ReheapDown(0, count -1) 5. return success End DeleteHeap 16
  • 17. <ErrorCode> DeleteHeap (ref MinData <DataType>) // Iterative version Removes the minimum element from the min-heap. Post MinData receives the minimum data in the heap and this data has been removed. The heap has been rearranged. Return underflow or success 1. if (heap is empty) 1. return underflow 2. else 1. MinData = Data[0] 2. lastElement = Data[count – 1] // The number of elements in the // heap is decreased so the last // element must be moved // somewhere in the heap. 17
  • 18. // DeleteHeap(cont.) // Iterative version 3. current_position = 0 4. continue = TRUE 5. loop (the element at the current_position has children) AND (continue = TRUE) 1. Let child is the smaller of two children 2. if (lastElement.key > child.key ) 1. Data[current_position] = child 2. current_position = current_position of child 3. else 1. continue = FALSE 6. Data[current_position] = lastElement 7. count = count - 1 8. return success End DeleteHeap 18
  • 19. Build heap <ErrorCode> BuildHeap (val listOfData <List>) Builds a heap from data from listOfData. Pre listOfData contains data need to be inserted into an empty heap. Post Heap has been built. Return overflow or success Uses Recursive function ReheapUp. 1. count = 0 2. loop (heap is not full) AND (more data in listOfData) 1. listOfData.Retrieve(count, newData) 2. data[count] = newData 3. ReheapUp( count) 4. count = count + 1 3. if (count < listOfData.Size() ) 1. return overflow 4. else 1. return success End BuildHeap 19
  • 20. Build heap Algorithm BuildHeap2 () Builds a heap from an array of random data. Pre Array of count random data. Post Array of data becames a heap. Uses Recursive function ReheapDown. 1. position = count / 2 -1 2. loop (position >=0) 1. ReheapDown(position, count-1) 2. position = position - 1 3. return End BuildHeap2 20
  • 21. Complexity of Binary Heap Operations 21
  • 22. d-heaps  d-heap is a simple generalization of a binary heap.  In d-heap, all nodes have d children.  d-heap improve the running time of InsertElement to O(logdn).  For large d, DeleteMin operation is more expensive: the minimum of d children must be found, which takes d-1 comparisons.  The multiplications and divisions to find children and parents are now by d, which increases the running time. (If d=2, use of the bit shift is faster).  d-heap is suitable for the applications where the number of Insertion is greater than the number of DeleteMin. 22
  • 23. Heap Applications Select Algorithms. Priority Queues. Heap sort (we will see in the Sorting Chapter). 23
  • 24. Select Algorithms Determine the kth largest element in an unsorted list Algorithm 1a: • Read the elements into an array, sort them. • Return the appropriate element. The running time of a simple sorting algorithm is O(n2) 24
  • 25. Select Algorithms Determine the kth largest element in an unsorted list Algorithm 1b: • Read k elements into an array, sort them. • The smallest of these is in the kth position. • Process the remaining elements one by one. • Compare the coming element with the kth element in the array. • If the coming element is large, the kth element is removed, the new element is placed in the correct place. The running time is O(n2) 25
  • 26. Select Algorithms Determine the kth largest element in an unsorted list Algorithm 2a: • Build a max-heap. • Detele k-1 elements from the heap. • The desired element will be at the top. The running time is O(nlog2n) 26
  • 27. Select Algorithms Determine the kth largest element in an unsorted list Algorithm 2b: • Build a min-heap of k elements. • Process the remaining elements one by one. • Compare the coming element with the minimum element in the heap (the element on the root of heap). • If the coming element is large, the minimum element is removed, the new element is placed in the correct place (reheapdown). The running time is O(nlog2n) 27
  • 28. Priority Queue ADT • Jobs are generally placed on a queue to wait for the services. • In the multiuser environment, the operating system scheduler must decide which of several processes to run. • Short jobs finish as fast as possible, so they should have precedence over other jobs. • Otherwise, some jobs are still very important and should also have precedence. These applications require a special kind of queue: a priority queue. 28
  • 29. Priority Queue ADT DEFINITION of Priority Queue ADT: Elements are enqueued accordingly to their priorities. Minimum element is dequeued first. Basic Operations: • Create • InsertElement: Inserts new data to the position accordingly to its priority order in queue. • DeleteMin: Removes the data with highest priority order. • RetrieveMin: Retrieves the data with highest priority order. 29 • Each element has a priority to be dequeued. • Minimum value of key has highest priority order.
  • 30. Priority Queue ADT Extended Operations: • Clear • isEmpty • isFull • RetrieveMax: Retrieves the data with lowest priority order. • IncreasePriority Changes the priority of some data • DecreasePriority which has been inserted in queue. • DeleteElement: Removes some data out of the queue. 30
  • 31. Specifications for Priority Queue ADT <ErrorCode> InsertElement (val DataIn <DataType>) <ErrorCode> DeleteMin (ref MinData <DataType>) <ErrorCode> RetrieveMin (ref MinData <DataType>) <ErrorCode> RetrieveMax (ref MaxData <DataType>) <ErrorCode> IncreasePriority (val position <int>, val PriorityDelta <KeyType>) <ErrorCode> DecreasePriority (val position <int>, val PriorityDelta <KeyType>) <ErrorCode> DeleteElement (val position <int>, ref DataOut <DataType>) <bool> isEmpty() <bool> isFull() <void> clear() 31
  • 32. Implementations of Priority Queue  Use linked list:  Simple linked list: • Insertion performs at the front, requires O(1). • DeleteMin requires O(n) for searching of the minimum data.  Sorted linked list: • Insertion requires O(n) for searching of the appropriate position. • DeleteMin requires O(1). 32
  • 33. Implementations of Priority Queue  Use BST: • Insertion requires O(log2 n). • DeleteMin requires O(log2 n). • But DeleteMin , repeatedly removing node in the left subtree, seem to hurt balance of the tree. 33
  • 34. Implementations of Priority Queue  Use min-heap: • Insertion requires O(log2 n). • DeleteMin requires O(log2 n). 34
  • 35. Insert and Remove element into/from priority queue <ErrorCode> InsertElement (val DataIn <DataType>): InsertHeap Algorithm <ErrorCode> DeleteMin (ref MinData <DataType>): DeleteHeap Algorithm 35
  • 36. Retrieve minimum element in priority queue <ErrorCode> RetrieveMin (ref MinData <DataType>) Retrieves the minimum element in the heap. Post MinData receives the minimum data in the heap and the heap remains unchanged. Return underflow or success 1. if (heap is empty) 1. return underflow 2. else 1. MinData = Data[0] 2. return success End RetrieveMin 36
  • 37. Retrieve maximum element in priority queue <ErrorCode> RetrieveMax (ref MaxData <DataType>) Retrieves the maximum element in the heap. Post MaxData receives the maximum data in the heap and the heap remains unchanged. Return underflow or success 1. if (heap is empty) 1. return underflow 2. else 1. Sequential search the maximum data in the right half elements of the heap (the leaves of the heap). The first leaf is at the position count/2. 2. return success End RetrieveMax 37
  • 38. Change the priority of an element in priority queue <ErrorCode> IncreasePriority (val position <int>, val PriorityDelta <KeyType>) Increases priority of an element in the heap. Post Element at position has its priority increased by PriorityDelta and has been moved to correct position. Return rangeError or success Uses ReheapDown. 38
  • 39. Change the priority of an element in priority queue <ErrorCode> DecreasePriority (val position <int>, val PriorityDelta <KeyType>) Decreases priority of an element in the heap. Post Element at position has its priority decreased by PriorityDelta and has been moved to correct position. Return rangeError or success Uses ReheapUp. 39
  • 40. Remove an element out of priority queue <ErrorCode> DeleteElement (val position <int>, ref DataOut <DataType>) Removes an element out of the min-heap. Post DataOut contains data in the element at position, this element has been removed. The heap has been rearranged. Return rangeError or success 1. if (position>=count ) OR (position <0) 1. return rangeError 2. else 1. DataOut = Data[position] 2. DecreasePriority(position, VERY_LARGE_VALUE), 3. DeleteMin(MinData) 4. return success End DeleteElement 40
  • 41. Advanced implementations of heaps  Advanced implementations of heaps: use of pointers  Leftist heap  Skew heap  Binomial queues Use of pointers allows the merge operations (combine two heaps into one) to perform easily. 41