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-1] 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–
int lo=0,mid=0,hi=n-1;
while(mid<=hi){
switch(A[mid]){
case 0:swap(A[lo++],A[mid++]); break;
case 1:mid++; break;
case 2:swap(A[mid],A[hi--]);
}
}
}
No comments:
Post a Comment