implemented recursive version of the algo