I need to add a single integer to a list that's already sorted, such that it goes in the right place. My first tought was something like
(sort (cons newelt list) #'<)
However, given that list
is already sorted, only one insertion is
really needed, which means this solution could be horribly unsuitable
depending on the algorithm used by sort
.
So, which is the algorithm that sort
uses?
Would I be better off doing something like the following?
(let ((tail list))
;; The first element is never less-than
(while (and tail (< newelt (cadr tail)))
(setq tail (cdr tail)))
(setcdr tail (cons newelt (cdr tail)))
list)
B
be initial already sortedlist
andA
andC
initially empty lists. SplitB
in two partsB1
,B2
of lengthsm
andm
orm+1
andm
, comparenewelt
to first element ofB2
. Ifnewelt
is≥
extendA
to its right withB1
and replaceB
withB2
, else extendC
to its left withB2
and replaceB
withB1
. AfterO(log n)
such steps nothing is left inB
. ThenA
contains the things≤ newelt
, andC
those> newelt
, and concatenation produces the extended sorted list. Apologies for not verye-lisp
like language.