sorted looping logic