orders three entries of an ArrayList at their specified indices assumes left <= mid <= right - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

orders three entries of an ArrayList at their specified indices assumes left <= mid <= right

Demo Code


import java.util.ArrayList;

public class Main{
    /**//from  w w w.  j a v  a2  s .co m
     * orders three entries of an ArrayList at their specified indices
     * assumes left <= mid <= right
     * 
     * @param arrayList the ArrayList whose three entries you want to sort
     * @param left the first of the three indices 
     * @param mid the second of the three indices
     * @param right the last of the three indices
     */
    public static <T extends Comparable<? super T>> void orderThreeEntries(
            ArrayList<T> arrayList, int left, int mid, int right) {
        if (arrayList.get(left).compareTo(arrayList.get(mid)) == 1) {
            ArrayListUtil.swap(arrayList, left, mid);
        }
        if (arrayList.get(mid).compareTo(arrayList.get(right)) == 1) {
            ArrayListUtil.swap(arrayList, mid, right);
        }
        if (arrayList.get(left).compareTo(arrayList.get(mid)) == 1) {
            ArrayListUtil.swap(arrayList, left, mid);
        }
    }
    /**
     * swaps two entries of an ArrayList
     * 
     * @param arrayList  the ArrayList whose entries you want to swap
     * @param yin  the index of the first swapped entry
     * @param yang  the index of the other swapped entry
     */
    public static <T extends Comparable<? super T>> void swap(
            ArrayList<T> arrayList, int yin, int yang) {
        T qi = arrayList.get(yin);
        arrayList.set(yin, arrayList.get(yang));
        arrayList.set(yang, qi);
    }
}

Related Tutorials