Skip to content

Commit ff724bb

Browse files
committed
base/sort: add sort! for multidimensional arrays
1 parent a2a1506 commit ff724bb

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

base/sort.jl

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -987,6 +987,51 @@ end
987987
Av
988988
end
989989

990+
"""
991+
sort!(A; dims::Integer, alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)
992+
993+
Sort the multidimensional array `A` along dimension `dims`.
994+
See [`sort!`](@ref) for a description of possible keyword arguments.
995+
996+
# Examples
997+
```jldoctest
998+
julia> A = [4 3; 1 2]
999+
2×2 Array{Int64,2}:
1000+
4 3
1001+
1 2
1002+
1003+
julia> sort!(A, dims = 1); A
1004+
2×2 Array{Int64,2}:
1005+
1 2
1006+
4 3
1007+
1008+
julia> sort!(A, dims = 2); A
1009+
2×2 Array{Int64,2}:
1010+
1 2
1011+
3 4
1012+
```
1013+
"""
1014+
function sort!(A::AbstractArray;
1015+
dims::Integer,
1016+
alg::Algorithm=defalg(A),
1017+
lt=isless,
1018+
by=identity,
1019+
rev::Union{Bool,Nothing}=nothing,
1020+
order::Ordering=Forward)
1021+
ordr = ord(lt, by, rev, order)
1022+
nd = ndims(A)
1023+
k = dims
1024+
1025+
1 <= k <= nd || throw(ArgumentError("dimension out of range"))
1026+
1027+
remdims = ntuple(i -> i == k ? 1 : size(A, i), nd)
1028+
for idx in CartesianIndices(remdims)
1029+
Av = view(A, ntuple(i -> i == k ? Colon() : idx[i], nd)...)
1030+
sort!(Av, alg, ordr)
1031+
end
1032+
A
1033+
end
1034+
9901035
## fast clever sorting for floats ##
9911036

9921037
module Float

0 commit comments

Comments
 (0)