finished recursive algorithm