# The `sort` only change order of the first column in matrix?

Hi friends,

I just found a strange behave of the method of `sort`

``````a1 = [
669.57  52.3
657.52  56.18
638.38  65.09
634.17  72.41
632.08  80.61]
sort(a1,dims=1)
``````

will give me below result

``````5×2 Matrix{Float64}:
632.08  52.3
634.17  56.18
638.38  65.09
657.52  72.41
669.57  80.61
``````

why the order of 2nd column donot change?

my Julia version is Version 1.9.3 (2023-08-24)

2 Likes

I think you’re looking for `sortslices`

5 Likes

Oh, I see. I just misunderstand the `sort` is sorting each row.

You explictly told Julia to sort columns with `dims=1`. Julia is column-major so the first dimension goes down the column. If you want to sort within the rows, use `dims=2`.

1 Like

That is generally the case also for row-major convention. Column/row-majority refers to memory layout, not indexing order.

1 Like

What’s wrong with using `sort` with `dims` keyword?

I think OP implicitly assumed a structure to his matrix where elements are grouped row-wise so sorting any column would mean all columns are sorted by the sorting order of that column (like when sorting a `DataFrame` by the values of a single column). E.g.

``````julia> x = [2 "b"; 1 "c"; 3 "a"]
3×2 Matrix{Any}:
2  "b"
1  "c"
3  "a"
``````

gives

``````julia> sort(x, dims = 1)
3×2 Matrix{Any}:
1  "a"
2  "b"
3  "c"
``````

with sort but

``````julia> sortslices(x, dims = 1)
3×2 Matrix{Any}:
1  "c"
2  "b"
3  "a"
``````

with sortslices (note the pairwise correspondence `1 => c, 2 => b, 3 => a` is retained here).

1 Like

Ah, perhaps. I say, that’s well reasoned, I would never have guessed.