Code for Algorithms 1