# Sorting lists with elements that are identical [closed]

How can I sort the following list:

list={{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,1776}, {1776, 1553}};


such that the next group contains one element of the first. The result would be:

{{1498, 1495}, {1552, 1495}, {1553, 1552}, {1776, 1553}, {1733,1776}, {1498, 1733}}

Sort[list,SameQ]


does not work completely as the results are still incorrectly sorted.

{{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,1776}, {1776, 1553}}


It does not matter if the elements are in increasing order. An equally acceptable result would be

{{1498, 1495}, {1498, 1733}, {1733, 1776}, {1776, 1553},{1553, 1552}, {1552, 1495}}

-

## closed as unclear what you're asking by Mr.Wizard♦Feb 7 at 15:28

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

Sorting with an equality test (SameQ) doesn't make sense. The test you used should be a ranking test (like OrderedQ, or Less) –  Sjoerd C. de Vries Feb 7 at 15:15
This question does not seem to be well specified, so I have closed to to prevent wasted efforts. Would you please describe the algorithm that you wish to implement, or the specific characteristics of the result that you wish to obtain? –  Mr.Wizard Feb 7 at 15:29

I am not sure if you still want the list to be sorted by increasing order at all. If not, here is a solution:

f[{a___, i_, j_, b___}] /;
i[[1]] =!= j[[1]] && i[[1]] =!= j[[2]] && i[[2]] =!= j[[1]] &&
i[[2]] =!= j[[2]] := f[{a, i, b, j}]

list = {{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,
1776}, {1776, 1553}};

f[list][[1]]


{{1498, 1495}, {1498, 1733}, {1733, 1776}, {1776, 1553}, {1553, 1552}, {1552, 1495}}

-
l = {{1498, 1495}, {1552, 1495}, {1553, 1552}, {1776, 1553}, {1733, 1776}, {1498, 1733}};
p = List @@@ First@FindHamiltonianCycle[Graph[UndirectedEdge @@@ l]];
p /. {x_, y_} :> {y, x} /; ! MemberQ[l, {x, y}]
(*
{{1498, 1495}, {1552, 1495}, {1553, 1552}, {1776, 1553}, {1733, 1776}, {1498, 1733}}
*)

-
I think an Eulerian cycle is what is desired here (we don't want to drop any edges). –  Rahul Narain Feb 7 at 16:20
@RahulNarain Thanks! I was waiting for an edit to clarify the question to understand what kind of cycle we should seek. –  belisarius Feb 7 at 16:43