The Selection Problem Revisited
We will show how to reduce this problem to the
following three:
•
the
Dutch national flag problem
;
•
the problem of finding a median; and
•
a smaller instance of itself.
The resulting algorithm will contain both iteration and
recursion.
1
The Dutch National Flag Problem
Input:
An array of items, each having a value of
red
,
white
, or
blue
.
Output:
A permutation of the items such that all
red
items precede all
white
items, which precede all
blue
items.
2
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
A Restriction
We will restrict the input to be an array of numbers.
For a given value
p
, we will consider a number
x
to be:
•
red
if
x < p
;
•
white
if
x
=
p
; or
•
blue
if
x > p
.
The problem is then to place all values less than
p
before all values equal to
p
, followed by all values
greater than
p
.
3
Specification for
DutchFlag
Precondition:
A
[
lo
..
hi
]
is an array of
Number
s,
lo
and
hi
are
Int
s such that
hi
≥
lo
−
1
, and
p
is a
Number
.
Postcondition:
A
[
lo
..
hi
]
is a permutation of its
original values such that all items less than
p
precede all
items equal to
p
, which in turn precede all items greater
than
p
. Returns an array
N
[1
..
3]
in which
N
[1]
is the
number of items less than
p
,
N
[2]
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '09
 Howell
 Postcondition, Selection algorithm, DUTCH NATIONAL FLAG, national flag problem

Click to edit the document details