Re: Insertion into sorted list
- To: mathgroup at smc.vnet.net
- Subject: [mg71071] Re: [mg71027] Insertion into sorted list
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Wed, 8 Nov 2006 06:11:59 -0500 (EST)
- References: <200611060752.CAA08537@smc.vnet.net>
On Nov 6, 2006, at 2:52 AM, 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)?
For a few insertions into a short list that's probably not a bad way
to do it. The following is occasionally slower but generally faster
for longer lists and more insertions:
insertSorted[lst_, elem_] := Block[{
l = Select[lst, # < elem &], p, len = Length[l]}, p = Length[l];
Join[l, {elem}, If[p < len, lst[[p + 1, len]], {}]]]
Regards,
Ssezi
- References:
- Insertion into sorted list
- From: "Andrew Moylan" <andrew.j.moylan@gmail.com>
- Insertion into sorted list