Some time ago I read a nice post Solving easy problems the hard way where linear regression is used to solve an interesting puzzle. Following the idea I used rpart to find optimal decision tree sorting five elements.
It is well known that in order to sort five elements it is enough to use seven comparisons. Interestingly it is possible to adjust rpart function to find the optimal decision tree.
To see this first let us start with generating the appropriate training data using the following code:
We get a data set with 120 rows. Each row contains a column perm5c representing one permutation of the set from 1 to 5 and 10 columns representing pairwise comparison results between variables. We want to find a decision tree that partitions this data set into one-element leaves with seven decisions in the worst case.
Simply applying rpart in the following way:
unfortunately generates a tree where ten decisions are neeeded in the worst case.
The trick to solve this problem is that you can supply rpart with your own split evaluation function. In this case the appropriate splitting rule should favour balanced splits (so for example 30-30 split is better than 40-20). Here is the code that does the work:
If you look at the output after printing tree.model you can see which paths lead to which classifications.
As you can see on the figure below at most seven comparisons are needed:
Additionally it is easy to modify the code to produce optimal trees for other numbers of elements to be sorted.