Implemented the algorithm