It does a sort by subnet distance. Therefore it compares the binary values of the ip address numbers with the clients current ip address. Then it ping the first five repositories and resorts them by ping time.
This resorting is not done everytime an agent connects to a repsoitory. It is only done when certain parameters are changed, e.g. the client ip address, someone added a new epo repository etc.