Java ListIterator Usage toposort(Iterable items, Comparator partOrder)

Here you can find the source of toposort(Iterable items, Comparator partOrder)

Description

Brute-force topological sort, required because element types are only partially ordered: there is no ordering amongst metamodel types nor amongst unrelated specialization types.

License

Open Source License

Parameter

Parameter Description
items the items to be sorted
partOrder a partial ordering relation on the items

Return

the topologically sorted items as a new mutable list

Declaration

private static <T> List<T> toposort(Iterable<T> items, Comparator<? super T> partOrder) 

Method Source Code


//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;
    }
}

Related

  1. toCharArrays(List strings)
  2. toInt(final List digits, final int base)
  3. toIntegerArray(List list)
  4. toLowerCase(List list)
  5. toLowerCase(List stringList)
  6. trimTail(List l)
  7. valueOf(E... elements)
  8. walkTo(String target, String path, int offset)