Complete implementation of both algorithms