Finished function to sort the variables for elimination.