1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
\errorcontextlines=100
\documentclass{article}
\usepackage{xfor}
\makeatletter
% \insertinto{new value}{list}
\newcommand{\insertinto}[2]{%
\def\nlst{}%
\@for\n:=#2\do{%
% store new list in \toks@
\expandafter\toks@\expandafter{\nlst}%
% test current value against new value
\ifnum\n>#1\relax
\edef\newstuff{\number#1,\n}%
% end for loop at the end of this iteration
\@endfortrue
\else
\edef\newstuff{\n}%
\fi
% append new stuff to new list
\ifx\nlst\@empty
\edef\nlst{\newstuff}%
\else
\edef\nlst{\the\toks@,\newstuff}%
\fi
}%
% check to see if for loop was prematurely terminated
\if@endfor
% loop may have been terminated during final iteration, in
% which case \@forremainder is empty.
\ifx\@forremainder\@empty
% do nothing
\else
% loop prematurely ended, append remainder of original list
% to new list
\expandafter\toks@\expandafter{\nlst}%
\edef\nlst{\the\toks@,\@forremainder}%
\fi
\else
% wasn't prematurely terminated, so new value hasn't been added
% add now.
\expandafter\toks@\expandafter{\nlst}%
\ifx\nlst\@empty
\edef\nlst{\number#1}%
\else
\edef\nlst{\the\toks@,\number#1}%
\fi
\fi
\global\let#2=\nlst
}
\newcommand{\insertionsort}[1]{%
\def\sortedlist{}%
\@for\val:=#1\do{{\insertinto{\val}{\sortedlist}}}%
\let#1=\sortedlist}
\makeatother
\begin{document}
\def\mylist{1,2,5,9,12,15,18,20}%
\def\newval{11}%
Original list: \mylist. New value: \newval.
\insertinto{\newval}{\mylist}
New list: \mylist.
Unsorted list:
\def\mylist{4,2,7,1,10,11,20,15}\mylist.
\insertionsort{\mylist}%
Sorted list: \mylist.
\end{document}
|