Teams are divided by the referees in an effort to keep the teams as balanced as possible. Often, referees will allow players to cluster into small groups and those groups are assigned to one of the two final teams.
A variety of factors go into the combination of groups, including age and experience.