All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.psjava.ds.set.DisjointSetForest Maven / Gradle / Ivy

package org.psjava.ds.set;

import org.psjava.ds.map.MutableMap;
import org.psjava.ds.map.MutableMapFactory;


public class DisjointSetForest {
	
	// see http://en.wikipedia.org/wiki/Disjoint-set_data_structure
	
	public static  DisjointSet create(MutableMapFactory mapFactory) {
		final MutableMap> infoMap = mapFactory.create();
		return new DisjointSet() {

			@Override
			public void makeSet(T value) {
				infoMap.put(value, new NodeInfo(value, 0));
			}

			@Override
			public void union(T x, T y) {
				T xrep = find(x);
				T yrep = find(y);
				if (xrep == yrep)
					return;
				NodeInfo xinfo = infoMap.get(xrep);
				NodeInfo yinfo = infoMap.get(yrep);
				if (xinfo.rank > yinfo.rank) {
					yinfo.parent = xrep;
				} else {
					xinfo.parent = yrep;
					if (xinfo.rank == yinfo.rank)
						yinfo.rank++;
				}
			}

			@Override
			public T find(T x) {
				NodeInfo info = infoMap.get(x);
				if (!info.parent.equals(x))
					info.parent = find(info.parent);
				return info.parent;
			}

		};
	}
	
	private static class NodeInfo {
		T parent;
		int rank;

		public NodeInfo(T p, int rank) {
			this.parent = p;
			this.rank = rank;
		}
	}

	private DisjointSetForest() {
	}
	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy