Algorithm for soring