# Visualize array changes with arrows

I want to visualize a sorting algorithm by highlighting the changes made in each step. E. g.:

[ a_1 a_2 a_3 a_4 ]
X
[ a_1 a_2 a_4 a_3 ]
X
[ a_1 a_4 a_2 a_3 ]


and so on.

Instead of the “X” I‘d like two arrows pointing from the center-bottom to the center-top of the elements would be better (but that‘s hard to do in ASCII at this solution, so I could not show that above …).

Additionally only neighbouring elements are exchanged, so I don‘t care for more complicating cases (e. g. exchanging a_1 with a_4 in the example above) for now. (But I do welcome answers which care for this point as well!)

How to do that with LaTeX? Show me beautiful arrow answers. :)

PS: Although I added an tikz-arrows tag I do welcome solutions which do not use tikz. But I thought most answers will use tikz anyway, so the tag should be unproblematic.

The basic structure could be a tikz matrix. Each row would be one step in your diagram. Once the matrix is created, its nodes are automatically named by their position inside the matrix, so you can draw arrows connecting them, or circles around them, or whatever. Of course the style of the arrow can be customized.

The following code shows an example. Note that, in order to delimit each row with brackets, a little trick was needed, because tikz interprets the brackets inside a matrix in a special way.

\usetikzlibrary{matrix}
\def\leftbracket{[}
\def\rightbracket{]}

\tikzset{my arrow/.style={
blue!60!black,
-latex
}
}

\begin{tikzpicture}
\matrix[matrix of math nodes, row sep=4mm] (M) {
\leftbracket & a_1 & a_2 & a_3 & a_4 & \rightbracket \\
\leftbracket & a_1 & a_2 & a_4 & a_3 & \rightbracket \\
\leftbracket & a_1 & a_4 & a_2 & a_3 & \rightbracket \\
};

\draw[my arrow] (M-3-3) to (M-2-4);
\draw[my arrow] (M-2-4) to (M-1-5);
\end{tikzpicture}


Result:

Another customization example, change the my arrow style to:

\tikzset{my arrow/.style={
blue!60!black,
->,
out=90, in=-90
}
}


Leaving the rest of the code as it was, the result is now:

• @Keba look at the update with curved arrows :-) – JLDiaz May 13 '14 at 18:12
• I also like your second solution, but at least in Ubuntu 12.04‘s texlive (version 2009) the “in” and “out” options do not seem to make any difference, ie. I still get the same arrows as in your first example- – Keba May 14 '14 at 0:00
• @Keba Note that I changed a bit the code in the answer, so that it can work with or without in/out options. When drawing the lines, instead of -- I use now to. – JLDiaz May 14 '14 at 7:18
• Ah, I see. That works well then. Thanks again. :) – Keba May 14 '14 at 9:54