Algorithm: priority queue

Preview:

Citation preview

Priority Queue

A priority queue is a data structure for

maintaining a set S of elements, each with

an associated value called a key.

Heap and Priority Queue

Heap can be used to implement a priority

queue.

Priority Queue

There are two kinds of priority queue

• max-priority queue

• min-priority queue

Priority Queue

Applications of priority queue

• Job scheduling on a shared computer

• Event-driven simulation

Priority Queue

A max-priority queue supports the following

operations

INSERT(S,x), MAXIMUM(S)

EXTRACT-MAX(S), INCREASE-KEY(S,x,k)

Priority Queue

HEAP-MAXIMUM(A)

return A[1]

Priority Queue

HEAP-EXTRACT-MAX(A)

if heap-size[A] < 1

then error “heap underflow”

max A[1]

A[1] A[heap-size[A]]

heap-size[A] heap-size[A]-1

MAX-HEAPIFY(A,1)

return max

Priority Queue

HEAP-INCREASE-KEY(A, i, key)

if key < A[i]

then error “new key is smaller than current key”

A[i] key

while i > 1 and A[PARENT(i)] < A[i]

do exchange A[i] A[PARENT(i)]

i PARENT(i)

Priority Queue

16

2

98

3

10

7

14

4 1

i

(a)

Priority Queue

16

2

98

3

10

7

14

15 1

i

(b)

Priority Queue

16

2

915

3

10

7

14

8 1

i

(c)

Priority Queue

16

2

914

3

10

7

15

8 1

i

(d)

Priority Queue

MAX-HEAP-INSERT(A, key)

heap-size[A] heap-size[A]+1

A[heap-size[A]] -∞

HEAP-INCREASE-KEY (A, heap-size[A], key)

Quick Sort

Divide: Partition the array into two sub-arrays

A[p . . q-1] and A[q+1 . . r] such that each element of

A[p . . q-1] is less than or equal to A[q], which in turn

less than or equal to each element of A[q+1 . . r]

Quick Sort

Conquer: Sort the two sub-arrays A[p . . q-1] and

A[q+1 . . r] by recursive calls to quick sort.

Quick Sort

Combine: Since the sub-arrays are sorted in place, no

work is needed to combine them.

Quick Sort

QUICKSORT(A, p, r)

if p< r

then q PARTITION(A, p, r)

QUICKSORT(A, p, q-1)

QUICKSORT(A, q+1, r)

Quick Sort

PARTITION(A, p, r)

x A[r]

i p-1

Quick Sort

for j p to r-1

do if A[j] <= x

then i i+1

exchange A[i] A[j]

exchange A[i+1] A[r]

return i+1

Quick Sort

i p, j r

2 8 7 1 3 5 6 4

(a)

Quick Sort

p, i j r

2 8 7 1 3 5 6 4

(b)

Quick Sort

p, i j r

2 8 7 1 3 5 6 4

(c)

Quick Sort

p, i j r

2 8 7 1 3 5 6 4

(d)

Quick Sort

p i j r

2 1 7 8 3 5 6 4

(e)

Quick Sort

p i j r

2 1 3 8 7 5 6 4

(f)

Quick Sort

p i j r

2 1 3 8 7 5 6 4

(g)

Quick Sort

p i r

2 1 3 8 7 5 6 4

(h)

Quick Sort

p i r

2 1 3 4 7 5 6 8

(i)

Recommended