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

org.hibernate.envers.internal.tools.graph.TopologicalSort Maven / Gradle / Ivy

/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or .
 */
package org.hibernate.envers.internal.tools.graph;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Topological sorting of a graph - based on DFS.
 *
 * @author Adam Warski (adam at warski dot org)
 */
public class TopologicalSort {
	private List sorted;
	private int time;

	private void process(Vertex v) {
		if ( v.getStartTime() != 0 ) {
			// alread processed
			return;
		}

		v.setStartTime( time++ );

		for ( Vertex n : v.getNeighbours() ) {
			process( n );
		}

		v.setEndTime( time++ );

		sorted.add( v.getRepresentation() );
	}

	public List sort(Collection> vertices) {
		sorted = new ArrayList<>( vertices.size() );

		time = 1;

		for ( Vertex v : vertices ) {
			if ( v.getEndTime() == 0 ) {
				process( v );
			}
		}

		Collections.reverse( sorted );

		return sorted;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy