Single loop version of the algorithm