Here you can find the source of toposort(Iterable
Parameter | Description |
---|---|
items | the items to be sorted |
partOrder | a partial ordering relation on the items |
private static <T> List<T> toposort(Iterable<T> items, Comparator<? super T> partOrder)
//package com.java2s; /*//from www . j a v a 2 s .c o m * Copyright (c) 2015 Christian W. Damus and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christian W. Damus - initial API and implementation */ import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; public class Main { /** * Brute-force topological sort, required because element types are only * partially ordered: there is no ordering amongst metamodel types nor * amongst unrelated specialization types. The only ordering relation is the * bottom-up vertex ordering in the specialization graph. * * @param items * the items to be sorted * @param partOrder * a partial ordering relation on the items * @return the topologically sorted {@code items} as a new mutable list */ private static <T> List<T> toposort(Iterable<T> items, Comparator<? super T> partOrder) { List<T> unsorted = new LinkedList<T>(); for (T next : items) { unsorted.add(next); } List<T> result = new ArrayList<T>(unsorted.size()); while (!unsorted.isEmpty()) { T min = unsorted.remove(0); for (ListIterator<T> iter = unsorted.listIterator(); iter.hasNext();) { T next = iter.next(); if (partOrder.compare(next, min) < 0) { // Found a new minimum. Put the old one back for next pass iter.set(min); min = next; } } // Whatever's the minimum now is the next in our partial ordering result.add(min); } return result; } }