I have array of arrays and I want to sort these arrays in array by their first element. Is something like this possible in Julia?
For example i have
a = (Array{Int64, 1})[]
push!(a, [5, 2 , 3])
push!(a, [3, 1 , 4])
And i want to sort in in way that the result will be [[3,1,4], [5,2,3]
. Arrays will be sorted according to their first element.
I need this because heap in Julia is unable to take arrays as element in heap. Any idea???
Update for version 1.0:
sort(a)
That's it. Julia version 1.0 defines <
for arrays to be the lexicographic sorting I describe below, so you don't need to manually specify it anymore.
Previous answer for 0.6
You can specify a custom lt
(less than) operator as a keyword argument to sort
:
julia> sort(a, lt=(x,y)->isless(x[1], y[1]))
2-element Array{Array{Int64,1},1}:
[3,1,4]
[5,2,3]
More generally, you can use lexless
to robustly sort the arrays in lexicographic order:
julia> push!(a, [5, 1, 1])
3-element Array{Array{Int64,1},1}:
[5,2,3]
[3,1,4]
[5,1,1]
julia> sort(a, lt=lexless)
3-element Array{Array{Int64,1},1}:
[3,1,4]
[5,1,1]
[5,2,3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With