4
$\begingroup$

What is the quickest way to sort a list of lists of integers, such that the first sorting criterion is the first element of the list, the next is the second element of the list and so on?

E.g. The list

list = {{1,3,4,5}, {1,2,4,3}, {1,1,2,8}, {1,3,5,6}, {1,2,3,4}}

would under these rules be sorted to

sortedlist = {{1,1,2,8}, {1,2,3,4}, {1,2,4,3}, {1,3,4,5}, {1,3,5,6}}

$\endgroup$

closed as off-topic by AccidentalFourierTransform, garej, Edmund, MarcoB, Henrik Schumacher Jul 3 at 19:34

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – AccidentalFourierTransform, garej, Edmund, MarcoB, Henrik Schumacher
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 4
    $\begingroup$ Simply Sort[list] , No ? $\endgroup$ – andre314 Jun 28 at 13:48
  • $\begingroup$ Yes, you're right - I was trying to do something more complicated than this simple example which was a list of lists of lists, but I could use this to do Table[Sort[list[[i]] , {i, 1, Length[list]}]. Thanks $\endgroup$ – nonreligious Jun 28 at 14:01
  • 3
    $\begingroup$ @nonreligious - Rather than use Table, map the Sort onto the list, i.e., Sort /@ list $\endgroup$ – Bob Hanlon Jun 28 at 14:09
6
$\begingroup$

If the sublists have equal lengths,

list[[Ordering[list]]]

{{1, 1, 2, 8}, {1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 4, 5}, {1, 3, 5, 6}}

With possibly unequal lengths:

list[[Ordering[PadRight @ list]]] 

{{1, 1, 2, 8}, {1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 4, 5}, {1, 3, 5, 6}}

$\endgroup$
  • $\begingroup$ I see, I had thought I would need to use SortBy[list, {#[[1]] &, #[[2]] &, #[[3]] &}] but this works. $\endgroup$ – nonreligious Jun 28 at 14:03
  • 1
    $\begingroup$ If the lengths are unequal the later parts that are being explicitly referenced may not exist. This would result in a Part::partw error message. $\endgroup$ – Bob Hanlon Jun 28 at 14:04
  • $\begingroup$ @BobHanlon, right. Ordering with PadRight works without that issue. $\endgroup$ – kglr Jun 28 at 14:06
3
$\begingroup$

With equal lengths, the simplest answer, as andre314 says in the comment above, is simply Sort:

Sort[list]

{{1, 1, 2, 8}, {1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 4, 5}, {1, 3, 5, 6}}

With unequal lengths, kglr's Ordering + PadRight approach is probably optimal.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.