简体   繁体   中英

Dutch Flag Problem (But do it with Two Colors)

If there were only two colors needed to be sorted in an array: Red (on the left) & White (on the right), would the following pseudocode make logical sense?

Pseudocode:

Pointer p & q , where p points to the first element and q points to the last element. p can only move right and q can only move left in the array.

while (p != q) {
   if (p->color != Red) {
     swap[p,q];
     q--;
   } else {
     p++;
   }
}

Yes that algorithm is correct.

A swap can only result in a yellow value at q , and q is not decremented as long as no swap happens. By consequence, all values occurring at the right side of q must be yellow.

Similarly, we can reason that if no swap happens, this means the value at p is red, and only in that case is p incremented. By consequence, all values occurring at the left of p are guaranteed to be red.

This is the loop invariant: all values at the left of p are red, and all values at the right of q are yellow.

When the loop exits we also know, in addition to the loop invariant, that p == q . There are two possibilities: either the value at that position is red or it is yellow. In either case the sorting is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM