Corrected the algorithm