Two Colours
It is easiest to consider just two "colours", {zero,one}, first. The algorithm maintains three sections (possibly empty) in the array a[ ]:
- a[1..Lo-1] zeroes
- a[Lo..Hi] unknown
- a[Hi+1..N] ones
- Lo := 1; Hi := N;
- while Lo <= Hi do
- Invariant: a[1..Lo-1] are all zero and a[Hi+1..N] are all one;
a[Lo..Hi] are unknown . - if a[Lo] = 0 then Lo++
- else swap a[Lo] and a[Hi]; Hi--
- Invariant: a[1..Lo-1] are all zero and a[Hi+1..N] are all one;
The problem was posed with three colours, here `0', `1' and `2'. The array is divided into four sections:
- a[1..Lo-1] zeroes (red)
- a[Lo..Mid-] ones (white)
- a[Mid..Hi] unknown
- a[Hi+1..N] twos (blue)
- Lo := 1; Mid := 1; Hi := N;
- while Mid <= Hi do
- Invariant: a[1..Lo-1]=0 and a[Lo..Mid-1]=1 and a[Hi+1..N]=2;
a[Mid..Hi] are unknown. - case a[Mid] in
- 0: swap a[Lo] and a[Mid]; Lo++; Mid++
- 1: Mid++
- 2: swap a[Mid] and a[Hi]; Hi--
- Invariant: a[1..Lo-1]=0 and a[Lo..Mid-1]=1 and a[Hi+1..N]=2;
No comments:
Post a Comment