improved sorting logic