Implemented first algorithm