 # Sorting a Matrix by column1 then column2

So I am currently working on a greedy heuristic for knapsack, representing the values and weights of items in a 2D array. Basically I have to reverse sort the matrix first by col1, which puts the most profitable items on top associated with their weights.
However, there are cases in which items have the same value, therefore the tiebreaker is the weight, so not only should I sort by the first column max to min, but also the second column from min to max.
For instance, if my unsorted matrix look something like this:
19 25
23 24
23 20
20 30
The output should be
23 20
23 24
20 30
19 25
My current implementation is something like this:

``````both_sorted = both[sortperm(both[:,1], rev=true),:]
``````

Is there a way to have an equivalent in Julia to this Python code?

``````both_sorted = sorted(both, key = lambda x: (x, x), reverse=True)
``````

I tried using dicts but they don’t admit duplicated values and I couldn’t get the catch of pairs.

The following seems to work with a minus sign trick:

``````M =[
19 25
23 24
23 20
20 30]

sortslices(M,dims=1,by=x->(x,-x),rev=true)

4×2 Matrix{Int64}:
23  20
23  24
20  30
19  25
``````
3 Likes

Thank you very much 