I am looking for a way to use Sort[]
to sort a collection of lists by comparing different parts of these lists. For example, sorting by comparing the second part of one list with the first part of another.
More specifically, given the list
list={{1, 4}, {2, 7}, {4, 6}, {5, 2}, {6, 5}, {7, 1}}
I would like to use Sort[]
to sort list
such that list[[1,2]]
equals list[[2,1]]
, list[[2,2]]
equals list[[3,1]]
, etc. giving output
{{1, 4}, {4, 6}, {6, 5}, {5, 2}, {2, 7}, {7, 1}}
I tried
Sort[list, (#1[[2]] == #2[[1]]) &]
but the output is
{{2, 7}, {7, 1}, {6, 5}, {5, 2}, {1, 4}, {4, 6}}
Repeatedly applying this sort function using Nest
or FixedPoint
did not give the output I wanted either.
Notice this problem is more general, as replacing ==
with <
or >
in my sort function does not sort the way one would expect either.
Though I know of ways to do this, I am looking for a nice, fast way, preferably using Sort
.
Reverse@Partition[Sort[list, (#1[[2]] == #2[[1]]) &], 2]~Flatten~1
$\endgroup$Partition[FindHamiltonianPath[DirectedEdge @@@ list], 2, 1, 1]
. Let me know if these suggestions work for you generally (i.e. try it on more complicated examples), and if so, I can write an answer. $\endgroup$list={{1, 2}, {2, 5}, {3, 1}, {5, 7}, {6, 3}, {7, 6}}
your function outputs{{1, 2}, {2, 5}, {7, 6}, {3, 1}, {6, 3}, {5, 7}}
when it should give{{1, 2}, {2, 5}, {5, 7}, {7, 6}, {6, 3}, {3, 1}}
. $\endgroup$List @@@ First@FindHamiltonianCycle[UndirectedEdge @@@ list]
. $\endgroup$