Improved the code for the algorithm