Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of arrays in Julia

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???

like image 747
M.Puk Avatar asked Dec 08 '22 23:12

M.Puk


1 Answers

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]
like image 51
mbauman Avatar answered Dec 11 '22 10:12

mbauman