MathGroup Archive 2006

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

Search the Archive

Re: Insertion into sorted list


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