Tikz-Arrows – Drawing Arrays Tree with TikZ for Visual Representation

tikz-arrowstikz-trees

I am trying to draw different kinds of recursive calls where arrays are sorted/manipulated etc. So I need to draw trees where the nodes can contain a sequence of elements.

Currently I am just drawing them in powerpoint and it should roughly look something like this (I took MERGE procedure as an example):

MERGE procedure

I saw a post here showing the entire Merge sort procedure in tikz, but that is not necessarily what I need. I need to be able to draw groups cells on each level and draw arrows between groups between levels. Currently I am using tikz for all trees.

Best Answer

Here is a solution using forest:

enter image description here

The basic idea is that the diagram is a tree that grows north (grow'=north) and has arrows pointing backwards (latex-). Each node (other than the leaves at the top) is a multi part node, defined using \tikzset with rectangle split.

\documentclass{article}

\usepackage{forest}
\usetikzlibrary {shapes.multipart}

\tikzset{multinode/.style={rectangle split, rectangle split horizontal, rectangle split parts=#1, anchor=center}}

\colorlet{c1}{yellow!30}
\colorlet{c2}{green!30}
\colorlet{c3}{red!30}
\colorlet{c4}{cyan!30}

\begin{document}

\begin{forest}
    for tree={grow'=north, l sep=7mm, edge={gray!70,very thick, latex-, shorten <=2pt, shorten >=2pt}, draw, anchor=center}
    [\nodepart{one}1\nodepart{two}1\nodepart{three}2\nodepart{four}2\nodepart{five}5\nodepart{six}7\nodepart{seven}7\nodepart{eight}8, multinode=8, {rectangle split part fill={c2,c4,c1,c3,c3,c1,c4,c2}}, for children={multinode=4}
        [\nodepart{one}1\nodepart{two}2\nodepart{three}7\nodepart{four}8, {rectangle split part fill={c2,c1,c1,c2}}, for children={multinode=2}
            [\nodepart{one}2\nodepart{two}7, fill=c1, for descendants={fill=c1}[7][2]]
            [\nodepart{one}1\nodepart{two}8, fill=c2, for descendants={fill=c2}[8][1]]
        ]
        [\nodepart{one}1\nodepart{two}2\nodepart{three}5\nodepart{four}7, {rectangle split part fill={c4,c3,c3,c4}}, for children={multinode=2}
            [\nodepart{one}2\nodepart{two}5, fill=c3, for descendants={fill=c3}[2][5]]
            [\nodepart{one}1\nodepart{two}7, fill=c4, for descendants={fill=c4}[7][1]]
        ]
    ]   
\end{forest}

\end{document}