corrected the execution flow of the algorithm