code for sorting forests