wards alg final function