Docsity

Priority Queues and Heaps - Object-Oriented Programming and Data Structures - Lecture Sl, Lecture notes of Object Oriented Programming

Partial preview of the text

Download Priority Queues and Heaps - Object-Oriented Programming and Data Structures - Lecture Sl and more Lecture notes Object Oriented Programming in PDF only on Docsity!

Priority

Queues

and

Heaps

The

Bag

Interface

•^ A

Bag:

interface

Bag

{

void

insert(E

obj);

E^ extract();

//extract

some

element

boolean

isEmpty();

} Examples: Stack, Queue, PriorityQueue

Priority

Queue

•^ A

Bag

in^

which

data

items

are

Comparable

•^ lesser

elements

(as

determined

by

compareTo()

)^ have

higher

priority

• extract()

returns

the

element

with

the

highest

priority

=^ least

in^

the

compareTo()

ordering • break

ties

arbitrarily

Priority

Queue

Examples

  • Scheduling jobs to run on a computer– default priority = arrival time– priority can be changed by operator• Scheduling events to be processed by anevent handler– priority = time of occurrence• Airline check-in– first class, business class, coach– FIFO within each class

Priority

Queues

as

Lists

  • Maintain as unordered list –^ insert()

puts new element at front – O(1)

-^ extract()

must search the list – O(n)

  • Maintain as ordered list –^ insert()

must search the list – O(n)

-^ extract()

gets element at front – O(1)

  • In either case, O(n

2 ) to process n elements

Can we do better?

Important

Special

Case

  • Fixed number of priority levels 0,...,p – 1• FIFO within each level• Example: airline check-in • insert()
    • insert in appropriate queue – O(1)
      • extract()
      • must find a nonempty queue – O(p)

Heaps

• Binary tree with data at each node• Satisfies the

Heap Order Invariant

• Size of the heap is “fixed” at

n.

(But can

The least (highest priority)element of any subtree is found atthe root of that subtreeusually double n if heap fills up)

Least element in any subtreeis always found at the rootof that subtree

Note: 19, 20 < 35: we can often findsmaller elements deeper in the tree!

Heaps

Balanced

Heaps

These add two restrictions:1. Any node of depth < d – 1 has exactly 2

children, where d is the height of the tree

–^

implies that any two maximal paths (path from a rootto a leaf) are of length d or d – 1, and the tree has atleast 2

d^ nodes

-^

All maximal paths of length d are to the left ofthose of length d – 1

Example

of

a^

Balanced

Heap^ d = 3

0

1

2

3

4

5

6

7

8

9

10

11

children of node n are found at 2n + 1 and 2n + 2

Store

in

an

ArrayList

or

Vector

Store

in

an

ArrayList

or

Vector

0

1

2

3

4

5

6

7

8

9

10

11

4

6

14

21

8

19

35

22

38

55

10

20

children of node n are found at 2n + 1 and 2n + 2

0 1

2

3

4

5

6

7

8

9

10

11 4

14

6 21

19 8

35

22

55 38

10

20

docsity.com

insert()

insert()