Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

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

Search the Archive

Re: Insertion into sorted list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg71105] Re: Insertion into sorted list
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Wed, 8 Nov 2006 06:15:52 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <eimq10$9b7$1@smc.vnet.net>

Andrew Moylan wrote:
> Hi all,
> 
> I have a sorted List. I need to occasionally insert new elements, while
> always keeping the list sorted. Is there a more efficient way to do
> this than the most obvious way (calling Append then calling Sort)?
> 
> Thanks for any help,
> 
> Andrew
> 
A combination of the built in functions *Insert* and *Position* should 
fit your needs:

In[1]:=
list = {2, 3, 5, 7, 13, 17};
With[{elem = 11}, list = Insert[list, elem,
      Position[list, _?(#1 >= elem & ), {1}, 1]]];
list

Out[3]=
{2, 3, 5, 7, 11, 13, 17}

Regards,
Jean-Marc


  • Prev by Date: Pythonika: Python in Mathematica
  • Next by Date: RE: building a list containing elements f(i,j)
  • Previous by thread: Re: Insertion into sorted list
  • Next by thread: Re: Insertion into sorted list