How to order a array of tuples

I have array of tuples and I want to ordered these tuples.

[(2, 3.1), (1, 5.5), (3, 4.5)]

for example, tuples can be ordered decreasing according to their first element.

[(3, 4.5),
 (2, 3.1),
 (1, 5.5)]

Is there a simple way to do this?

You can simply run sort() on a vector of tuples, and if you want a decreasing order the you can pass rev=true :

julia> t = [(2, 3.1), (1, 5.5), (3, 4.5)]
3-element Array{Tuple{Int64,Float64},1}:
 (2, 3.1)
 (1, 5.5)
 (3, 4.5)

julia> sort(t, rev=true)
3-element Array{Tuple{Int64,Float64},1}:
 (3, 4.5)
 (2, 3.1)
 (1, 5.5)
3 Likes

Alternatively to @rdeits’s solution, you can do

julia> sort([(2, 3.1), (1, 5.5), (3, 4.5)], by = first, rev = true)
3-element Array{Tuple{Int64,Float64},1}:
 (3, 4.5)
 (2, 3.1)
 (1, 5.5)

which will only consider the first element.

2 Likes

@Tamas_Papp, @rdeits Thank you so much for your help.

sort works only for the first element?

A further example would be to order this array:

t = [(3, 2), (2, 2), (2, 1), (1, 3), (1, 2), (1, 1)]

And I would like to sort it so that the first elements remain in the same order i.e. 3, 2, 2, 1, 1, 1, but the second elements are ordered the opposite way so it’s like this:

[(3, 2), (2, 1), (2, 2), (1, 1), (1, 2), (1, 3)]

i.e. the tuples are ordered such that the first elements are in decreasing order and where the first element is the same the tuples are ordered with second elements in increasing order.

No, it works by comparing elements with isless by default. isless is defined lexicographically for tuples. You can reverse that (as @rdeits suggested), or just explicitly compare the first element (as I suggested).

define a custom comparison function, eg

sort(those_tuples,
     lt = (x, y) -> (x[1] > y[1] || (x[1] == y[1] && x[2] < y[2]))
1 Like