RE: sort list
- To: mathgroup at smc.vnet.net
- Subject: [mg47224] RE: [mg47208] sort list
- From: "E. Martin-Serrano \(Houston - USA\)" <eMartinSerrano at houston.rr.com>
- Date: Wed, 31 Mar 2004 02:58:11 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
Guido,
The following two functions will answer your question in full,
The first one sorts a table for any c-th column. It was once posted at
MathGroup.
(* 'CTableSort' sorts table (matrix t) for c-th column. *)
CTableSort[ t_?MatrixQ, col_Integer]/;col<=Dimensions[t][[2]]:=
Sort[t,#1[[col]]> #2[[col]]& ]
The second one (FTableSort) is a bit elaborated, and perhaps inefficient.
But for small to medium size tables is good enough to sort tables in full,
starting at a first column, then for the second...
(* 'FTableSort' sorts table (matrix t) for 1th column, then for 2th, ...
then for i-th column, ... and finally for n-th column. *)
FTableSort[t_?MatrixQ,c_:0]:=
Module[{col = c, pos = i = i1 = i2 = head = tsi = tb= {}, numcols =
Length[ First[t]]},
col++;
If[col\[Equal]1,tsf={}];
tsi=CTableSort[t,col];
If[Or [col \[Equal] numcols ,Length[tsi]\[Equal]1],AppendTo[tsf
,#]&/@tsi;Return[tsf]];
i= Transpose[Frequencies[Column[tsi,col]]//Reverse]//First;
i1 =FoldList[(#1+#2)&,1,Delete[i,-1]];
i2 =FoldList[(#1+#2)&,First[i],Rest[i]];
pos=MapThread[{#1,#2}&,{i1,i2}];
poshead = First[pos];
If[Length[pos]\[Equal] 1, postail = head,postail = Rest[pos]];
If[First[poshead]\[Equal]1 && Last[poshead]\[Equal]1,AppendTo[tsf
,First[tsi]];FTableSort[#,col]&/@(Take[tsi,#]&/@postail),FTableSort[#,col]&/
@(Take[tsi,#]&/@pos)];
tsf
];
Cheers,
Emilio
-----Original Message-----
From: Guibout [mailto:guibout at ifrance.com]
To: mathgroup at smc.vnet.net
Subject: [mg47224] [mg47208] sort list
Hi,
I have a list of the form
{{something1,x1},{something2,x2},{something3,x3}} where x1,x2, x3 are
numbers. I want to sort this list with respect to xi. In other word if
x2<x3<x1 I want Mathematica to produce:
{{something2,x2},{something3,x3},{something1,x1}}
Thanks for your help
Vincent