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