Sort ArrayList Write the following method that sorts an Arra
(Sort ArrayList) Write the following method that sorts an ArrayList: public static >
void sort(ArrayList list
JAVA
Solution
import java.util.ArrayList;
/**
 * @author
 *
 */
 public class GenericSort {
   /**
    * method to sort the list
    *
    * @param list
    */
    public static <E extends Comparable<E>> void sort(ArrayList<E> list) {
        Object currentMax;
        int currentMaxIndex;
       for (int i = list.size() - 1; i >= 1; i--) {
            // Find the maximum in the list[0..i]
            currentMax = list.get(i);
            currentMaxIndex = i;
           for (int j = i - 1; j >= 0; j--) {
                if (((Comparable) currentMax).compareTo(list.get(j)) < 0) {
                    currentMax = list.get(j);
                    currentMaxIndex = j;
                }
            }
           // Swap list[i] with list[currentMaxIndex] if necessary;
            if (currentMaxIndex != i) {
                list.set(currentMaxIndex, list.get(i));
                list.set(i, (E) currentMax);
           }
        }
}
   /**
    * @param args
    */
    public static void main(String[] args) {
        Integer[] intArray = { new Integer(2), new Integer(4), new Integer(3) };
       // Create a String List
        ArrayList<String> stringList = new ArrayList<String>();
        stringList.add(\"Srinivas\");
        stringList.add(\"Pavan\");
        stringList.add(\"Kishore\");
        stringList.add(\"Rajesh\");
        stringList.add(\"Charkri\");
       // Create a int List
        ArrayList<Integer> intList = new ArrayList<Integer>();
        intList.add(20);
        intList.add(30);
        intList.add(10);
        intList.add(40);
        intList.add(90);
        intList.add(50);
       System.out.println(\"Before sorting :\");
        System.out.println(stringList);
        System.out.println(intList);
       // Sort the arrays
        sort(stringList);
        sort(intList);
       System.out.println(\"After sorting :\");
        System.out.println(stringList);
        System.out.println(intList);
}
}
OUTPUT:
Before sorting :
 [Srinivas, Pavan, Kishore, Rajesh, Charkri]
 [20, 30, 10, 40, 90, 50]
 After sorting :
 [Charkri, Kishore, Pavan, Rajesh, Srinivas]
 [10, 20, 30, 40, 50, 90]


