The Dutch Flag Problem

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...

Do a traversal over your data, saving 3 indices: Note that the unsorted cells are always between afterBlue and beforeWhite.
At each step of your traversal, check the color of the cell at afterBlue and do the required exchanges. The loop ending condition is when afterBlue becomes larger than beforeWhite.