Sorting using Priority Queues
Selection sort
-it uses an unsorted-list priority queue
Phase 1: insert items from sequence
s
into priority queue
p
.
Phase 2: Remove items from
p
one by one and insert them into
s
.
S = {5, 9, 3, 6}
P = { }
Phase 1: insert items from s into p
S = { } P = {5, 9, 3, 6} O(n)
Phase 2: remove items from p one by one and insert into s. Find the minimum value
first and remove from p then place into s.
S = {3} P = {5, 9, 6} O (n) 1
S = {3, 5} P = {9, 6} O (n) 2
S = {3, 5, 6} P = {9} O (n) 3
S = {3, 5, 6, 9}P = { } O (n) 4
= O (n
2
)
And ta da! S is sorted.
Insertion Sort
-it uses a priority queue with a sorted sequence
-it uses the same steps as selection sort; the only difference is that it uses a
sorted sequence.
S = {5, 9, 3, 6} P = { }
Phase 1: remove items from
s
and insert into
p
in order
S = {9, 3, 6} P = {5}
S = {3, 6} P = {5, 9}
S = {6} P = {3, 5, 9}
S = { } P = {3, 5, 6, 9}
This step is O (n
2
)
Phase 2: remove items from P and put back into S
S = {3, 5, 6, 9} P = { }
This step is O (n)

This
** preview**
has intentionally

**sections.**

*blurred***to view the full version.**

*Sign up*
Both selection and insertion sort will take O (n
2
)
-Selection sort will always take a number of operations proportional to O (n
2
)

This is the end of the preview.
Sign up
to
access the rest of the document.