implemenattion of algorithm