Re: Is Sort stable?
- To: mathgroup at smc.vnet.net
- Subject: [mg39743] Re: [mg39725] Is Sort stable?
- From: BobHanlon at aol.com
- Date: Wed, 5 Mar 2003 00:04:56 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
In a message dated 3/4/03 1:25:41 AM, rolle at ifm.liu.se writes:
> --Short form:
> Is the sorting algorithm implemented by Sort[] stable?
>
> --Long form:
> I'm doing a thingy where I need to take out subsets of data and look at
> them
> individually. I have a labeled data set, with labels being a vector of 1,2
> ... denoting class membership, and I've tried to pick out subset using
> either e.g.
>
> Extract[data, Position[labels,1]]
> => the data points in "class 1"
>
> or using Sort to sort data according to labels (so I get e.g. {1,1,1,1, ...
> 2,2,2, ... 3,3,3}, and which is nice for plotting data sets. This work ok,
> but it seems like Sort[] is rearranging the data points within classes
> different from Extract[]. Does anyone know i Is the Sort[] algorithm
> stable?
> Could there be something else lurking here?
>
>
data = Table[
{Random[Integer,{1,3}],Random[Integer,{1,3}],Random[]},
{20}]
The default is a multi-position sort
Sort[data]
Sorting solely by the first position reverses the order of the elements
within the individual groupings
Sort[data, #1[[1]]<#2[[1]]&]
To use Sort and leave the order within groupings untouched
Sort[Reverse[data], #1[[1]]<#2[[1]]&]
Verifying,
%==Flatten[Table[
Extract[data,Position[data,{n,_,_}]],
{n,3}], 1]
or alternatively
%%==Flatten[Table[
Cases[data, {n,_,_}], {n,3}],1]
Bob Hanlon