COL 106
Shweta Agrawal and Amit
Kumar
Revisiting FindMin
Application: Find the smallest ( or
highest priority) item quickly
Operating system needs to schedule
jobs according to priority instead of FIFO
Event simulation (bank customers
arriving and departing, ordered
according to when the event happened)
Find student with highest grade,
employee with highest salary etc.
What if we use
Lists: If sorted, what is the run time for Insert
and FindMin? Unsorted?
Binary Search Trees: What is the run time for
Insert and FindMin?
Hash Tables: What is the run time for Insert
and FindMin?
Hash Tables
Insert O(1) but no hope for FindMin
Binary Heaps
A binary heap is a binary tree (NOT a BST)
that is:
Complete: the tree is completely filled except
possibly the bottom level, which is filled from
left to right
Satisfies the heap order property
5
10
94
10
97
min
value
97
24
24
Structure property
A binary heap is a complete tree
All nodes are in use except for possibly
the right end of the bottom row
Examples
6
4
2
2
complete tree,
heap order is "max"
2
4
7
not complete
2
6
5
complete tree,
heap order is "min"
5
7
6
4
index
N=5
7
4
6
5
11
4
7
DeleteMin:
Delete (and return)
value at root node
3
5
10
11 9 6 14
12
DeleteMin
4
7
3
5
10
11 9 6 14
13
4
7
3
5
10
11 9 6 14
4
7
3
5
10
11 9 6 14
14
14
3
5
10
11 9 6
15
?
4
7
3
5
11 9 6
14
3
4
4
10
7
11 9 6
10
8
5
14
10
11 9 6
6 | 10 | 8 | 13 | 14 | 25
Percolate Down
PercDown(i:integer, x: integer): {
// N is the number elements, i is the hole,
x is the value to insert
Case{
2i > N : A[i] := x; //at bottom//
no children
2i = N : if A[2i] < x then
one child
A[i] := A[2i]; A[2i] := x;
at the end
else A[i] := x;
2i < N : if A[2i] < A[2i+1] then j := 2i;
2 children
else j := 2i+1;
if A[j] < x then
A[i] := A[j]; PercDown(j,x);
else A[i] := x;
}}
12/26/03
17
18
Insert
Add a value to the
tree
Structure and heap
order properties
must still be correct
when we are done
2
3
4
7
8
5
14
10
11 9 6
19
2
3
4
7
8
5
14
10
11 9 6
20
3
4
7
8
5
14
10
11 9 6
2
21
Insert: Percolate Up
3
4
7
11 9 6
8
5
14 10
?
2
7
11 9 6
14
?
8
10
7
11 9 6
14
10
Insert: Done
2
3
7
11 9 6
8
4
14
10
Run time?
23
Time
FindMin: O(1)
DeleteMin and Insert: O(log N)
BuildHeap from N inputs ???
12/26/03
24
Build Heap
BuildHeap {
for i = N/2 to 1
PercDown(i, A[i])
}
N=11
11
2
4
9
8
12/26/03
2 7 6
9
10
11
6
10
8
3
11
12
9
2 7 6
10
3
12
25
Build Heap
11
11
5
2
9 7 6
12/26/03
10
3
8
4
5
9
2
9 7 6
8
3
10
12
26
Build Heap
11
2
5
9 7 6
12/26/03
8
3
10
4
3
12
8
4
10
12
9 7 6 11
27
Time Complexity
Nave considerations:
n/2 calls to PercDown, each takes
clog)n)
Total:
29
32
33
12/26/03
34
12/26/03
35