Docsity

Binary Heaps: Data Structures and Operations, Slides of Data Structures and Algorithms

Toggle sidebar
bg1
Priority Queue
Anton Apostolatos
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25

Partial preview of the text

Download Binary Heaps: Data Structures and Operations and more Slides Data Structures and Algorithms in PDF only on Docsity!

Priority Queue

Anton Apostolatos

Queue: order items by when they were placed - first in, first

out ( FIFO )

Function

s

enqueue

dequeue

first

size

isEmpty

Unsorted List

PQueue

Sorted Singly-Linked

List

Unsorted Doubly-Linked

List

Binary

Heap

Binary

Heap

Slides by Chris Gregg!

Binary Heaps

There are two types of heaps:
Min Heap
(root is the smallest element)

12

22 43

5

11

8

10

14 13

2

17

7

50

3

36

19

25 1

Max Heap
(root is the largest element)

Binary Heaps (Min Heap)

K

All K All K

Binary Heaps

Circle the min-heap(s):

22

12

11

5

85

8

10

14 13

25

24

26

13

99

36

19

46 42

Binary Heaps

Circle the min-heap(s):

22

12

11

5

85

8

10

14 13

25

24

26

13

99

36

19

46 42

Binary Heaps

What is the best way to store a

heap?

12

5

11

8

10

13

14

22 43

We could use a node-based solution, but…

Binary Heaps

It turns out that an array works great

for storing a binary heap!

We will put the root at index 1 instead of

index 0 (this makes the math work out just

a bit nicer).

12

22 43

5

11

8

10

13

14

5 10 8 12 11 14 13 22 43

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

Heap Operations

  • min() : return an element of h with the

smallest key.

  • insert(e) : insert element e into the

heap.

  • removeMin() : removes the smallest

element from h.

12

22 43

5

11

8

10

13

14

Heap Operations: min()

min()

Just return the root!

return heap[1] 12

22 43

5

11

8

10

13

14

5 10 8 12 11 14 13 22 43

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

Heap Operations: insert(k)

Insert item at element array[heap.size()+1]

(this probably destroys the heap property)

Perform a “ bubble up ” or “ up-heap ”

operation:

Compare the added element with its parent

if in correct order, stop

If not, swap and repeat

Heap Operations: insert(k)

12

22 43

5

11

8

10

13

14

12

22 43

5

11

8

10

13

14

5 10 8 12 11 14 13 22 43

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

Start by inserting the key at the first empty

position. This is always at index

heap.size()+.

Heap Operations: insert(9)