Finished the algorithm