implemented union find algorithm