Implementing the algorithm