It's been a long time but I am pretty sure I remember... I believe it looks for groups of consecutive people with either the same pants or the same shirt and moves the largest group it can find to the back of the line.
I cannot remember what it does in case of a tie, unfortunately.