Java tutorial
//package com.java2s; /* * Copyright (c) 2016. * This file is part of OFlib. * * OFlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OFlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OFlib. If not, see <http://www.gnu.org/licenses/>. */ import java.util.*; public class Main { /** * Sorts a collection using a comparator and returns it as a {@link List} * * @param c Collection to be sorted * @param k Comparator to sort by * @param reverse Whether to reverse the sort order * @return a {@link List} of the sorted elements * @throws IllegalAccessException when unable to access the comparator class * @throws InstantiationException when unable to instantiate to comparator class */ public static <E> List<E> sortByCompare(Collection<E> c, Class<? extends Comparator<E>> k, boolean reverse) throws IllegalAccessException, InstantiationException { Comparator<E> comp = k.newInstance(); int moves = 0; boolean firstRun = true; LinkedList<E> l = new LinkedList<>(c); while (moves > 0 || firstRun) { firstRun = false; moves = 0; for (int i = 1; i < l.size(); i++) { E a = l.get(i - 1); E b = l.get(i); if (reverse ? comp.compare(a, b) < 0 : comp.compare(a, b) > 0) { l.set(i - 1, b); l.set(i, a); moves++; } } } return l; } }