MathGroup Archive 2006

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

Search the Archive

Re: Insertion into sorted list

  • To: mathgroup at
  • Subject: [mg71071] Re: [mg71027] Insertion into sorted list
  • From: Sseziwa Mukasa <mukasa at>
  • Date: Wed, 8 Nov 2006 06:03:41 -0500 (EST)
  • References: <>

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]], {}]]]



  • Prev by Date: Help needed
  • Next by Date: Question about trig simplify
  • Previous by thread: Insertion into sorted list
  • Next by thread: Re: Insertion into sorted list