Download presentation
Presentation is loading. Please wait.
Published byDina Walton Modified over 6 years ago
1
Binary Heaps Text Binary Heap Building a Binary Heap
Read Weiss, § Binary Heap One-array representation of a tree Complete trees Building a Binary Heap Insert Delete
2
Motivation Development of a data structure which allows efficient inserts and efficient deletes of the minimum value (minheap) or maximum value (maxheap)
3
Implementation One-array implementation of a binary tree
Root of tree is at element 1 of the array If a node is at element i of the array, then its children are at elements 2*i and 2*i+1 If a node is at element i of the array, then its parent is at element floor(i/2)=└ i/2┘
4
Implementation 4 12 5 26 25 14 15 29 45 35 31 21 i array __ __ __ __ currentsize = 12
5
Implementatation Heap must be a complete tree
all leaves are on the lowest two levels nodes are added on the lowest level, from left to right nodes are removed from the lowest level, from right to left
6
Inserting a Value 4 12 5 26 25 14 15 29 45 35 31 21 3 Insert 3
insert here to keep tree complete i array __ __ __ currentsize = 13 Insert 3
7
Inserting a Value 4 12 5 26 25 14 15 29 45 35 31 21 3 Insert 3
save new value in a temporary location: tmp 3 Insert 3
8
Inserting a Value 4 12 5 26 25 14 15 29 45 35 31 21 14 3 Insert 3
copy 14 down because 14 > 3 3 tmp Insert 3
9
Inserting a Value 4 12 5 26 25 12 15 29 45 35 31 21 14 3 Insert 3
copy 12 down because 12 > 3 3 tmp Insert 3
10
Inserting a Value 4 4 5 26 25 12 15 29 45 35 31 21 14 3 Insert 3
copy 4 down because 4 > 3 3 tmp Insert 3
11
Inserting a Value 3 4 5 26 25 12 15 29 45 35 31 21 14 Insert 3
12
Heap After Insert 3 4 5 26 25 12 15 29 45 35 31 21 14
13
Deleting a Value (note new tree!)
3 7 5 26 25 12 15 29 45 35 31 21 14 Delete 3
14
Deleting a Value 7 5 26 25 12 15 29 45 35 31 21 14 3 Delete 3
save root value … tmp 3 Delete 3
15
X Deleting a Value 14 7 5 26 25 12 15 29 45 35 31 21 14 3 Delete 3
copy value of last node in complete tree into temporary location; decrement currentsize 14 7 5 26 25 12 15 X 29 45 35 31 21 14 tmp 3 Delete 3
16
compare children select smaller
Deleting a Value 14 push down root … compare children select smaller 7 5 26 25 12 15 29 45 35 31 21 tmp 3 Delete 3
17
copy smaller value into parent
Deleting a Value 14 5 push down root … copy smaller value into parent 7 26 25 12 15 29 45 35 31 21 tmp 3 Delete 3
18
compare children select smaller (25)
Deleting a Value 14 5 push down root … 7 26 25 12 15 29 45 35 31 21 compare children select smaller (25) tmp 3 Delete 3
19
copy 14 into parent because 14 < smaller child
Deleting a Value 5 push down root … 7 14 26 25 12 15 29 45 35 31 21 copy 14 into parent because 14 < smaller child tmp 3 Delete 3
20
Deleting a Value 5 7 14 26 25 12 15 29 45 35 31 21 return 3 Delete 3
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.