Social psychology is devoted to the study of groups, so of course it makes sense that someone would study how groups are formed. The interesting thing is, it doesn't take much for people to begin assigning people to groups, including themselves. This is called the minimal group paradigm - how much information about others do we need before we start assigning them to our own group or different groups, and to show favoritism to our own group? And the answer is: not much.
This effect was demonstrated by a researcher named Henri Tajfel. His first work on the subject, in 1971, involved two studies - one in which people were randomly assigned to a group (which they were told was based on performance on task, though they were actually assigned at random) and another where participants selected which of two paintings they preferred.
In both studies, participants were then grouped with others and could assign cash awards to the other group members. Unsurprisingly, people in the same performance group or who liked the same painting received higher cash awards than different groups or people who liked the other painting.
Even when people know that group assignment was random, they still favor their own group. In fact, there's a great XKCD cartoon on the subject that I know I've blogged before. But here it is again: