move sorting logic outside loop