implemented the algorithm