Your work is to sort all the colors of the Dutch flag, and the only provided primitive is to exchange two given lines. In addition, you should not create any additional variables (but a few indices).
If you think carefully, this can be done in linear time, where you sort a line at each iteration of the loop. You may want to check again the insertion sort, of which the Dutch Flag sort is a variation. The main difference is that you have 3 insertion points, not only one...
afterBlue
is initialized to 0. Make sure that every cell below afterBlue
is filled with blue elements.whiteRed
is initialized to size-1. Make sure that every cell after whiteRed
is filled with red elements.beforeWhite
is initialized to size-1. Make sure that every cell after beforeWhite
and before whiteRed
is filled with while elements.afterBlue
and beforeWhite
.afterBlue
and do the required exchanges.
The loop ending condition is when afterBlue
becomes larger than beforeWhite
.