








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An in-depth explanation of heaps, a crucial data structure in computer science. Topics covered include the definition of max-heaps and min-heaps, building a heap, heap class interface, cost analysis of siftdown and buildheap, deleting the root of a heap, and heap sort. Useful for students preparing for exams, quizzes, or assignments related to data structures and algorithms.
Typology: Essays (university)
1 / 14
This page cannot be seen from the preview
Don't miss anything!









©2000 McQuain WD
Data Structures & File Management
Heaps^ A max-heap is a complete binary tree in which the value in each internal nodeis greater than or equal to the values in the children of that node.A min-heap is defined similarly.
Mapping the elementsof a heap into an arrayis trivial:if a node is stored atindex k, then its leftchild is stored at index2k+1 and its rightchild at index 2k+
©2000 McQuain WD
Data Structures & File Management
Building a Heap^ The fact that a heap is a complete binary tree allows it to be efficientlyrepresented using a simple array.Given an array of N values, a heap containing those values can be built,
in situ
,
by simply “sifting” each internal node down to its proper location:
-^
-^
-^
-^
*****^
©2000 McQuain WD
Data Structures & File Management
BuildHeap
and
SiftDown
As described earlier:^ template void HeapT::BuildHeap() {
for (int Idx = numVertices/2 - 1; Idx >= 0; Idx--)
SiftDown(Idx); } template void HeapT::SiftDown(int toSift) {
while ( !isLeaf(toSift) ) {
int MaxChild = leftChild(toSift);if ( (MaxChild < numVertices - 1) &&
(Hp[MaxChild] < Hp[MaxChild + 1]) )MaxChild++; if (Hp[toSift] >= Hp[MaxChild]) return;Item tmpItem = Hp[toSift];Hp[toSift] = Hp[MaxChild];Hp[MaxChild] = tmpItem;toSift = MaxChild; } }
Determine which child nodeis larger See if node must sift downIf so, swap it with its largerchild (maintaining heapproperty),and continue sifting down…
Why is Idxinitialized thisway?
©2000 McQuain WD
Data Structures & File Management
Cost of
SiftDown
In a complete binary tree of N nodes, the number of levels is at most 1 + log(N).Since each non-terminating iteration of the loop moves the target value adistance of 1 level, the loop will perform no more than log(N) iterations.Thus, the worst case cost of
SiftDown()
is O(log N).
template void HeapT::SiftDown(int toSift) {
while ( !isLeaf(toSift) ) {
int MaxChild = leftChild(toSift);if ( (MaxChild < numVertices - 1) &&
(Hp[MaxChild] < Hp[MaxChild + 1]) )MaxChild++; if (Hp[toSift] >= Hp[MaxChild]) return;Item tmpItem = Hp[toSift];Hp[toSift] = Hp[MaxChild];Hp[MaxChild] = tmpItem;toSift = MaxChild; } }
In the worst case, weperform two elementcomparisons……and one element swap periteration That’s 2log(N) comparisonsand log(N) swaps.
©2000 McQuain WD
Data Structures & File Management
In the worst case, the number of comparisons BuildHeap() will require inbuilding a heap of N nodes is given by:Since, at worst, there is one swap for each two comparisons, the maximumnumber of swaps is N –
élog N
ù.
Hence, building a heap of N nodes is O(N) in both comparisons and swaps.
d
d k
d k
k
k
d k
k
©2000 McQuain WD
Data Structures & File Management
Deleting the Root of a Heap^ We will see that the most common operation on a heap is the deletion of theroot node. The heap property is maintained by sifting down…^ template Item HeapT::RemoveRoot() {
if (numVertices == 0) return Item();Item tmpItem = Hp[0];Hp[0] = Hp[numVertices - 1];Hp[numVertices - 1] = tmpItem;numVertices--;SiftDown(0);return tmpItem; }
Check for empty heapSwap the root with the lastleaf, andshrink the heap by one node.Sift the new root down torestore the heap property.
Why is the last leaf chosen as thereplacement for the root?
©2000 McQuain WD
Data Structures & File Management
Heap Sort^ A list can be sorted by first building it into a heap, and then iteratively deletingthe root node from the heap until the heap is empty. If the deleted roots arestored in reverse order in an array they will be sorted in ascending order (if amax heap is used).^ void HeapSort(int* List, int Size) {
HeapT toSort(List, Size);toSort.BuildHeap();int Idx = Size - 1;while ( !toSort.isEmpty() ) {
List[Idx] = toSort.RemoveRoot();Idx--; } }
©2000 McQuain WD
Data Structures & File Management
Cost of Deleting the Roots^ Recalling the earlier analysis of building a heap, level k of a full and completebinary tree will contain 2
k^ nodes, and that those nodes are k levels below the
root level.So, when the root is deleted the maximum number of levels the swapped nodecan sift down is the number of the level from which that node was swapped.Thus, in the worst case, for deleting all the roots…
(^
) [^
]
é^
ù^
é^
ù^
N N
N N
d
k
k^
d
d k
k
d k
k
4
log 2
log 2
1 (^22)
4 2 4 2 2 s
Comparison
1
(^11)
1
(^11)
−
=
=
=^
−
− =
−
− =
å
å
As usual, with Heap Sort, this would entail half as many element swaps.
©2000 McQuain WD
Data Structures & File Management
Priority Queues^ A
priority queue
consists of entries, each of which contains a key field, called
the
priority
of the entry.
Aside from the usual operations of creation, clearing, tests for full and empty,and reporting its size, a priority queue has only two operations:
-^
insertion of a new entry
-^
removal of the entry having the largest (or smallest) key
Key values need not be unique. If not, then removal may target any entryholding the largest value.
©2000 McQuain WD
Data Structures & File Management
Representation^ Representation of a priority queue may be achieved using:
-^
a sorted list, but…
-^
an unsorted list, but…
-^
a max-heap
Priority queues may be used to manage prioritized processes in a time-sharingenvironment, time-dependent simulations, and even numerical linear algebra.