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:08:53 -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: Re: Evaluating integral with varying upper limit?
  • 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