SlideShare une entreprise Scribd logo
1  sur  28
Data Structures & Algorithms
Heapsort
Heaps
A heap is data
structure that can be
viewed as a nearly
complete binary tree
 Each node
corresponds to an
element of an array
that stores its
values
 The tree is
completely filled on
all levels except the
lowest
2 4 1
8 7 9 3
1414 10
16
Heaps
Heaps are typically stored using arrays
 The array is of size length(A)
 heapsize(A) elements are currently in use
 A[1] is the “root” node of the tree
 Any element x has the following properties:
 Parent(x) is x/2
 Left(x) is 2*x
 Right(x) is 2*x+1
16 14 10 8 7 9 3 2 4 1
1 2 3 4 5 6 7 8 9 10
The Heap Property
Heaps satisfy what is known as the heap
property:
 For a max-heap, the heap property is:
 A[Parent(x)] >= A[x]
 I.e., the root node of the tree or any subtree has a
larger value than any node in its subtrees
 This is reversed for min-heaps:
 A[Parent(x)] <= A[x]
 I.e., the smallest element is at the root
Terminology
Height of a node = number of edges
that must be traversed to get from that
node to a leaf
Height of a tree = height of the root =
O(lg n)
Basic heap operations generally take
O(lg n), because they are based on the
height of the tree
Maintaining the Heap Property
MaxHeapify is a routine used to maintain the
max-heap property of an array
 It takes as input the array to heapify, the element
to begin with, and the number of elements in the
heap
 Assumes Left(x) and Right(x) are heaps, but the
tree rooted at x may not be, thus violating the
heap property
 The idea is to propagate x through the tree into
it’s proper position
MaxHeapify
MaxHeapify(A, x, heapsize)
{
L = Left(x)
R = Right(x)
if ( L < heapsize && A[L] > A[x] )
Largest = L
else
Largest = x
if ( R <= heapsize && A[R] > A[Largest] )
Largest = R
if ( Largest != x )
{
swap(A[x], A[Largest])
MaxHeapify(A, Largest, heapsize)
}
}
MaxHeapify In Action
Here, the red node is out of place, violating
the heap property
2 8 1
14 7 9 3
144 10
16
MaxHeapify In Action
After calling MaxHeapify(A, 2, 10), the red
node is pushed further down the heap
2 8 1
4 7 9 3
1414 10
16
MaxHeapify In Action
After calling MaxHeapify(A, 4, 10), the heap is now
correct – a further call to MaxHeapify(A, 9, 10) will
yield no further changes
2 4 1
8 7 9 3
1414 10
16
Building a Heap
Given an unsorted array, we can build a
heap recursively from the bottom-up
using this algorithm:
BuildMaxHeap(A, size)
{
for ( x = length(A)/2 ; x >= 1 ; --x )
MaxHeapify(A, x, size)
}
Building a Heap
14 8 7
2 16 9 10
141 3
4
1
2 3
4 5 6 7
8 9 10
Building a Heap
14 8 7
2 16 9 10
141 3
4
1
2 3
4 5 6 7
8 9 10
Building a Heap
2 8 7
14 16 9 10
141 3
4
1
2 3
4 5 6 7
8 9 10
Building a Heap
2 8 7
14 16 9 3
141 10
4
1
2 3
4 5 6 7
8 9 10
Building a Heap
2 8 7
14 1 9 3
1416 10
4
1
2 3
4 5 6 7
8 9 10
Building a Heap
2 8 1
14 7 9 3
1414 10
16
1
2 3
4 5 6 7
8 9 10
Analysis of BuildMaxHeap
How long does it take?
 MaxHeapify has cost O(lgn), and is called O(n)
times, so intuitively there’s O(nlgn)
 This isn’t an asymptotically tight bound, though
 The MaxHeapify cost isn’t really based on n
 It’s cost is based on the height of the node in the tree
 An n-element heap has height lgn, and at most n/2h+1
nodes of any height h
 The math at this point gets a bit complicated, but
results in a running time of O(n) (see pg. 145
(old)/135 (new))
The HeapSort Algorithm
The HeapSort algorithm sorts an array by
using a max-heap as an intermediate
step
 First, a max-heap is built from the input
 The max element is exchanged with
A[heapsize], to put it in its final position
 The remainder of the array is then re-
heapified, using heapsize - 1
The HeapSort Algorithm
HeapSort(A, size)
{
BuildHeap(A, size)
For ( x = size ; x >= 2 ; --x )
{
swap(A[1], A[x])
--heapsize
Heapify(A, 1, x-1)
}
}
What is the running time of HeapSort?
Analysis of HeapSort
In practice, the HeapSort will usually be
beat by QuickSort
The heap data structure has a number of
other uses, however
Priority Queues
One use of a heap is as a priority queue
Priority queues are often used in an OS to
perform job/resource scheduling
 Also in simulators, and many other tasks
A priority queue is a data structure for
maintaining a set of elements (S), each with
an associated value called a key
 Priority queues come in two flavors: max-priority
queues and min-priority queues
Priority Queues
Max-priority queues support these
operations:
 Insert(S, x) – inserts x into S
 Maximum(S) – returns the element in S with the
largest key
 ExtractMax(S) – removes and returns the element
in S with the largest key
 IncreaseKey(S, x, k) – increases the value of
element x’s key to the new value k
Priority Queuess
HeapMaximum(A)
{
return A[1];
}
Priority Queues
HeapExtractMax(A, heapsize)
{
if ( heapsize < 1 )
throw HeapUnderflowError();
max = A[1];
A[1] = A[heapsize];
--heapsize;
MaxHeapify(A, 1, heapsize);
return max;
}
Priority Queues
HeapIncreaseKey(A, i, key)
{
if ( key < A[i] )
throw HeapKeyError();
A[i] = key;
while ( i > 1 && A[Parent(i) < A[i] )
{
swap(A[i], A[Parent(i)]);
i = Parent(i);
}
}
Priority Queues
MaxHeapInsert(A, key, heapsize)
{
++heapsize;
A[heapsize] = -MAXKEY;
HeapIncreaseKey(A, A[heapsize], key);
}
Exercises
1st Edition:
 Pg 142: 7.1-1, 7.1-2, 7.1-6
 Pg 144: 7.2-1, 7.2-2, 7.2-4
 Pg 150: 7.5-3, 7.5-5
2nd Edition
 Pg 129: 6.1-1, 6.1-2, 6.1-6
 Pg 132: 6.2-1, 6.2-3, 6.2-5
 Pg 142: 6.5-6, 6.5-7

Contenu connexe

Tendances (20)

4 heapsort pq
4 heapsort pq4 heapsort pq
4 heapsort pq
 
Heaps
HeapsHeaps
Heaps
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Heapsort ppt
Heapsort pptHeapsort ppt
Heapsort ppt
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
 
Heaps
HeapsHeaps
Heaps
 
Heapsort
HeapsortHeapsort
Heapsort
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Heapsort quick sort
Heapsort quick sortHeapsort quick sort
Heapsort quick sort
 
Heap Sort Algorithm
Heap Sort Algorithm Heap Sort Algorithm
Heap Sort Algorithm
 
Heap sort
Heap sortHeap sort
Heap sort
 
Heaps
HeapsHeaps
Heaps
 
Heapsort
HeapsortHeapsort
Heapsort
 
Heap tree
Heap treeHeap tree
Heap tree
 
3.7 heap sort
3.7 heap sort3.7 heap sort
3.7 heap sort
 
DataStructure Concepts-HEAP,HASH,Graph
DataStructure Concepts-HEAP,HASH,GraphDataStructure Concepts-HEAP,HASH,Graph
DataStructure Concepts-HEAP,HASH,Graph
 
05 heap 20161110_jintaeks
05 heap 20161110_jintaeks05 heap 20161110_jintaeks
05 heap 20161110_jintaeks
 
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
 
Heap Data Structure
 Heap Data Structure Heap Data Structure
Heap Data Structure
 
Heapsort
HeapsortHeapsort
Heapsort
 

Similaire à Cis435 week05

Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingTraian Rebedea
 
lecture 5
lecture 5lecture 5
lecture 5sajinsc
 
lecture 6
lecture 6lecture 6
lecture 6sajinsc
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heapschidabdu
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdfNash229987
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfssuser034ce1
 
week2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptx
week2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptxweek2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptx
week2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptxhardmarcelia
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).pptSudhaPatel11
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).pptAmitShou
 
21. Heap_new.ppt
21. Heap_new.ppt21. Heap_new.ppt
21. Heap_new.pptAryanGour1
 
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
 
heap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsheap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsssuser7319f8
 
Max priority queue
Max priority queueMax priority queue
Max priority queue9854098540
 
III_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxIII_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxshashankbhadouria4
 

Similaire à Cis435 week05 (20)

Algorithms - "heap sort"
Algorithms - "heap sort"Algorithms - "heap sort"
Algorithms - "heap sort"
 
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
 
lecture 5
lecture 5lecture 5
lecture 5
 
Unit III Heaps.ppt
Unit III Heaps.pptUnit III Heaps.ppt
Unit III Heaps.ppt
 
lecture 6
lecture 6lecture 6
lecture 6
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdf
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
 
week2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptx
week2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptxweek2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptx
week2.v2 dsfjue0owirewoifudsoufsoiuewrew.pptx
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
21. Heap_new.ppt
21. Heap_new.ppt21. Heap_new.ppt
21. Heap_new.ppt
 
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
 
Heap Tree.pdf
Heap Tree.pdfHeap Tree.pdf
Heap Tree.pdf
 
Stack and Hash Table
Stack and Hash TableStack and Hash Table
Stack and Hash Table
 
heap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsheap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithms
 
heapsort_bydinesh
heapsort_bydineshheapsort_bydinesh
heapsort_bydinesh
 
Max priority queue
Max priority queueMax priority queue
Max priority queue
 
III_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxIII_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptx
 

Plus de ashish bansal (14)

Data struters
Data strutersData struters
Data struters
 
Cis435 week04
Cis435 week04Cis435 week04
Cis435 week04
 
Cis435 week03
Cis435 week03Cis435 week03
Cis435 week03
 
Cis435 week02
Cis435 week02Cis435 week02
Cis435 week02
 
Cis435 week01
Cis435 week01Cis435 week01
Cis435 week01
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
35 algorithm-types
35 algorithm-types35 algorithm-types
35 algorithm-types
 
32 algorithm-types
32 algorithm-types32 algorithm-types
32 algorithm-types
 
7 stacksqueues
7 stacksqueues7 stacksqueues
7 stacksqueues
 
5 searching
5 searching5 searching
5 searching
 
4 recursion
4 recursion4 recursion
4 recursion
 
Cis435 week06
Cis435 week06Cis435 week06
Cis435 week06
 

Dernier

Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 

Dernier (20)

Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 

Cis435 week05

  • 1. Data Structures & Algorithms Heapsort
  • 2. Heaps A heap is data structure that can be viewed as a nearly complete binary tree  Each node corresponds to an element of an array that stores its values  The tree is completely filled on all levels except the lowest 2 4 1 8 7 9 3 1414 10 16
  • 3. Heaps Heaps are typically stored using arrays  The array is of size length(A)  heapsize(A) elements are currently in use  A[1] is the “root” node of the tree  Any element x has the following properties:  Parent(x) is x/2  Left(x) is 2*x  Right(x) is 2*x+1 16 14 10 8 7 9 3 2 4 1 1 2 3 4 5 6 7 8 9 10
  • 4. The Heap Property Heaps satisfy what is known as the heap property:  For a max-heap, the heap property is:  A[Parent(x)] >= A[x]  I.e., the root node of the tree or any subtree has a larger value than any node in its subtrees  This is reversed for min-heaps:  A[Parent(x)] <= A[x]  I.e., the smallest element is at the root
  • 5. Terminology Height of a node = number of edges that must be traversed to get from that node to a leaf Height of a tree = height of the root = O(lg n) Basic heap operations generally take O(lg n), because they are based on the height of the tree
  • 6. Maintaining the Heap Property MaxHeapify is a routine used to maintain the max-heap property of an array  It takes as input the array to heapify, the element to begin with, and the number of elements in the heap  Assumes Left(x) and Right(x) are heaps, but the tree rooted at x may not be, thus violating the heap property  The idea is to propagate x through the tree into it’s proper position
  • 7. MaxHeapify MaxHeapify(A, x, heapsize) { L = Left(x) R = Right(x) if ( L < heapsize && A[L] > A[x] ) Largest = L else Largest = x if ( R <= heapsize && A[R] > A[Largest] ) Largest = R if ( Largest != x ) { swap(A[x], A[Largest]) MaxHeapify(A, Largest, heapsize) } }
  • 8. MaxHeapify In Action Here, the red node is out of place, violating the heap property 2 8 1 14 7 9 3 144 10 16
  • 9. MaxHeapify In Action After calling MaxHeapify(A, 2, 10), the red node is pushed further down the heap 2 8 1 4 7 9 3 1414 10 16
  • 10. MaxHeapify In Action After calling MaxHeapify(A, 4, 10), the heap is now correct – a further call to MaxHeapify(A, 9, 10) will yield no further changes 2 4 1 8 7 9 3 1414 10 16
  • 11. Building a Heap Given an unsorted array, we can build a heap recursively from the bottom-up using this algorithm: BuildMaxHeap(A, size) { for ( x = length(A)/2 ; x >= 1 ; --x ) MaxHeapify(A, x, size) }
  • 12. Building a Heap 14 8 7 2 16 9 10 141 3 4 1 2 3 4 5 6 7 8 9 10
  • 13. Building a Heap 14 8 7 2 16 9 10 141 3 4 1 2 3 4 5 6 7 8 9 10
  • 14. Building a Heap 2 8 7 14 16 9 10 141 3 4 1 2 3 4 5 6 7 8 9 10
  • 15. Building a Heap 2 8 7 14 16 9 3 141 10 4 1 2 3 4 5 6 7 8 9 10
  • 16. Building a Heap 2 8 7 14 1 9 3 1416 10 4 1 2 3 4 5 6 7 8 9 10
  • 17. Building a Heap 2 8 1 14 7 9 3 1414 10 16 1 2 3 4 5 6 7 8 9 10
  • 18. Analysis of BuildMaxHeap How long does it take?  MaxHeapify has cost O(lgn), and is called O(n) times, so intuitively there’s O(nlgn)  This isn’t an asymptotically tight bound, though  The MaxHeapify cost isn’t really based on n  It’s cost is based on the height of the node in the tree  An n-element heap has height lgn, and at most n/2h+1 nodes of any height h  The math at this point gets a bit complicated, but results in a running time of O(n) (see pg. 145 (old)/135 (new))
  • 19. The HeapSort Algorithm The HeapSort algorithm sorts an array by using a max-heap as an intermediate step  First, a max-heap is built from the input  The max element is exchanged with A[heapsize], to put it in its final position  The remainder of the array is then re- heapified, using heapsize - 1
  • 20. The HeapSort Algorithm HeapSort(A, size) { BuildHeap(A, size) For ( x = size ; x >= 2 ; --x ) { swap(A[1], A[x]) --heapsize Heapify(A, 1, x-1) } } What is the running time of HeapSort?
  • 21. Analysis of HeapSort In practice, the HeapSort will usually be beat by QuickSort The heap data structure has a number of other uses, however
  • 22. Priority Queues One use of a heap is as a priority queue Priority queues are often used in an OS to perform job/resource scheduling  Also in simulators, and many other tasks A priority queue is a data structure for maintaining a set of elements (S), each with an associated value called a key  Priority queues come in two flavors: max-priority queues and min-priority queues
  • 23. Priority Queues Max-priority queues support these operations:  Insert(S, x) – inserts x into S  Maximum(S) – returns the element in S with the largest key  ExtractMax(S) – removes and returns the element in S with the largest key  IncreaseKey(S, x, k) – increases the value of element x’s key to the new value k
  • 25. Priority Queues HeapExtractMax(A, heapsize) { if ( heapsize < 1 ) throw HeapUnderflowError(); max = A[1]; A[1] = A[heapsize]; --heapsize; MaxHeapify(A, 1, heapsize); return max; }
  • 26. Priority Queues HeapIncreaseKey(A, i, key) { if ( key < A[i] ) throw HeapKeyError(); A[i] = key; while ( i > 1 && A[Parent(i) < A[i] ) { swap(A[i], A[Parent(i)]); i = Parent(i); } }
  • 27. Priority Queues MaxHeapInsert(A, key, heapsize) { ++heapsize; A[heapsize] = -MAXKEY; HeapIncreaseKey(A, A[heapsize], key); }
  • 28. Exercises 1st Edition:  Pg 142: 7.1-1, 7.1-2, 7.1-6  Pg 144: 7.2-1, 7.2-2, 7.2-4  Pg 150: 7.5-3, 7.5-5 2nd Edition  Pg 129: 6.1-1, 6.1-2, 6.1-6  Pg 132: 6.2-1, 6.2-3, 6.2-5  Pg 142: 6.5-6, 6.5-7