MathGroup Archive 1999

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: easiest way to sort a list?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg18322] Re: [mg18308] easiest way to sort a list?
  • From: "Carl K.Woll" <carlw at fermi.phys.washington.edu>
  • Date: Sat, 26 Jun 1999 19:08:02 -0400
  • Organization: Department of Physics
  • References: <199906260224.WAA14461@smc.vnet.net.>
  • Sender: owner-wri-mathgroup at wolfram.com

Peter,

Here is one idea.

OrderedUnion[li_]:=Block[{i},
    i[n_]:=(i[n]=Sequence[];n);
    i /@ li]

The first time the function i hits an integer, it returns that integer. After
that, it returns Sequence[], which disappears. I had another idea, where I
adjoined an auxiliary index list, then sorted and unioned using appropriate
tests. This idea was slightly faster for short lists. However, for longer
lists, it was slower, as the sorting algorithm is O(n log(n)), and the function
OrderedUnion is O(n).

Carl Woll
Physics Dept
U of Washington

Peter T. Wang wrote:

> Hi everyone,
>
> Here's my question:  Suppose you have a list of integers, not all distinct,
> say
>       {1, 5, 3, 5, 10, 10, 1},
>
> and you want to obtain the list
>
>       {1, 5, 3, 10}
>
> which is the set of distinct elements but with the order preserved; i.e.,
> the order in which the elements in the second list appear is the same as
> the order in which it first occurs in the first list.  What is a simple
> way to do this?  Evidently Union[] sorts the elements in canonical order,
> which is not desirable.  My current solution is so messy that I suspect
> there must be an easier way.
>
> -peter





  • Prev by Date: One more question :)
  • Next by Date: Re: RE: easiest way to sort a list?
  • Previous by thread: easiest way to sort a list?
  • Next by thread: Re: easiest way to sort a list?