Java tutorial
//package com.java2s; /* * File: CollectionUtil.java * Authors: Justin Basilico * Company: Sandia National Laboratories * Project: Cognitive Foundry * * Copyright March 25, 2008, Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the U.S. Government. Export * of this program may require a license from the United States Government. * See CopyrightHistory.txt for complete details. * */ import java.util.ArrayList; import java.util.Comparator; public class Main { /** * Swaps the indices "a" and "b" in the array "indices" if the corresponding * data values data[indices[a]] is greater than data[indices[b]]. * @param <ComparableType> Type of data to compare to. * @param a first index * @param b second index * @param indices array of indices to index into "data", which is * modified by this method. * @param data ArrayList of values, unchanged. * @param comparator Comparator used to determine if two values * are greater than, less than, or equal to each other. * @return * True if swapped, false if left alone. */ private static <ComparableType> boolean swapIfAGreaterThanB(int a, int b, int[] indices, ArrayList<? extends ComparableType> data, Comparator<? super ComparableType> comparator) { final boolean doSwap = comparator.compare(data.get(indices[a]), data.get(indices[b])) > 0; if (doSwap) { swapArrayValues(a, b, indices); } return doSwap; } /** * Swaps the two indexed values in the indices array. * @param i1 First index * @param i2 Second index * @param indices Array of indices to swap */ private static void swapArrayValues(int i1, int i2, int[] indices) { int temp = indices[i1]; indices[i1] = indices[i2]; indices[i2] = temp; } }