The algorithm for sorting into pairs