# Sorting a Matrix by column1 then column2

**URL:** https://discourse.julialang.org/t/sorting-a-matrix-by-column1-then-column2/55980
**Category:** General Usage
**Tags:** sort, arrays
**Created:** [February 25, 2021, 4:23am UTC](https://discourse.julialang.org/t/sorting-a-matrix-by-column1-then-column2/55980 "2021-02-25T04:23:35Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![eduardosalaz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eduardosalaz/32/22287_2.png) [@eduardosalaz](https://discourse.julialang.org/u/eduardosalaz)
#### Post date: [February 25, 2021, 4:23am UTC](https://discourse.julialang.org/t/sorting-a-matrix-by-column1-then-column2/55980/1 "2021-02-25T04:23:36Z")

</div>

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:

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

```

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

```julia
both_sorted = sorted(both, key = lambda x: (x[0], x[1]), reverse=True)

```

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

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [February 25, 2021, 8:51am UTC](https://discourse.julialang.org/t/sorting-a-matrix-by-column1-then-column2/55980/2 "2021-02-25T08:51:03Z")

</div>

The following seems to work with a minus sign trick:

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

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

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

```

---

<div class="post-metadata">

### Author: ![eduardosalaz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eduardosalaz/32/22287_2.png) [@eduardosalaz](https://discourse.julialang.org/u/eduardosalaz)
#### Post date: [February 25, 2021, 3:24pm UTC](https://discourse.julialang.org/t/sorting-a-matrix-by-column1-then-column2/55980/3 "2021-02-25T15:24:34Z")

</div>

Thank you very much 😄
