Professional Documents
Culture Documents
Riley
Porter
Winter
2017
Pseudocode
PracGce
Come
up
with
pseudocode
for
the
following
algorithm:
Algorithm:
Given
a
list
of
integers,
find
the
index
of
the
maximum
integer
in
the
list.
• OperaGons:
6
2
– insert
15
23
– deleteMin
insert
12
18
deleteMin
– is_empty
45
3
7
40
60
85
99
30
40
400
50
700
are
these
trees
complete?
CSE373:
Data
Structures
&
Winter
2017
19
Algorithms
Structure
Property:
Completeness
• A
Binary
Heap
is
a
complete
binary
tree:
– A
binary
tree
with
all
levels
full,
with
a
possible
excepGon
being
the
bomom
level,
which
is
filled
lej
to
right
incomplete
Examples:
10
complete
10
20
80
20
80
40
60
85
99
30
40
400
50
700
CSE373:
Data
Structures
&
Winter
2017
20
Algorithms
Heap
Order
Property
• The
priority
of
every
(non-‐root)
node
is
greater
than
(or
equal
to)
that
of
it's
parent.
AKA
the
children
are
always
greater
than
the
parents.
10
1
20 80 30 33
20 40 400 40 20 40 800
20 80 30 33
20 40 400 40 20 40 800
2
1.
Delete
(and
later
4
3
return)
value
at
root
7
5
8
9
node
11
9
6
10
Winter
2017
CSE373:
Data
Structures
&
Algorithms
28
2.
Restore
the
Structure
Property
4 3 4 10 4 8
7 5 8 9 7 5 8 9 7 5 10 9
11 9 6 11 9 6 11 9 6
Percolate down:
• Keep comparing with both children
• Swap with lesser child and go down one level
• What happens if we swap with the larger child?
• Done if both children are ≥ item or reached a leaf node
Winter
2017
CSE373:
Data
Structures
&
Algorithms
3
Insert
1
• Ajerwards,
structure
and
heap
properGes
must
sGll
4
8
be correct 7 5 10 9
11 9 6
more node 4 8
7 5 10 9
Winter
2017
CSE373:
Data
Structures
&
Algorithms
Maintain
the
heap
property
1
1
1
?
1
4 8 4 8 2 8
7
5
10
9
7
2
10
9
7
4
10
9
?
?
11
9
6
2
11
9
6
5
11
9
6
5
5
4
Percolate up:
• Put new data in new location
• If parent larger, swap with parent, and continue
• Done if parent ≤ item or reached root
Winter
2017
CSE373:
Data
Structures
&
Algorithms
3
Array
RepresentaGon
of
Binary
Trees
A B C D E F G H I J K L
0 1 2 3 4 5 6 7 8 9 10 11 12 13