1

I have 3 selection sort methods in my code that I pass an ArrayList of Integers, Doubles, and Strings too, but I was wondering if there was a way to alter my method to accept any type of ArrayList that I pass to it. Because if I try to change it to ArrayList Object then I cannot use a < or > comparison inside.

Here's what I have (which only works for ArrayLists of Integers):

 private static ArrayList<Integer> selection_sort(ArrayList<Integer> arr) {
    for (int i = 0; i < arr.size(); i++) {
        int pos = i;
        for (int j = i; j < arr.size(); j++) {
            if (arr.get(j) < arr.get(pos))
                pos = j;
        }
        int min = arr.get(pos);
        arr.set(pos, arr.get(i));
        arr.set(i, min);
    }
    return arr;
 }
Luke H
  • 27
  • 1
  • 6

2 Answers2

2

You could make it work for any generic type T which is also Comparable. Just add the generic type and modify your method to invoke compareTo. Like,

private static <T extends Comparable<? super T>> ArrayList<T> selection_sort(
            ArrayList<T> arr) {
    for (int i = 0; i < arr.size(); i++) {
        int pos = i;

        for (int j = i; j < arr.size(); j++) {
            if (arr.get(j).compareTo(arr.get(pos)) < 0)
                pos = j;
        }

        T min = arr.get(pos);
        arr.set(pos, arr.get(i));
        arr.set(i, min);
    }
    return arr;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    Another option is to pass `Comparator comparator` as a second argument and use `Collections.sort(arr, comparator);` as a method body. The `ArrayList` arg type can be weakened to the `List`. – Vladimir Vagaytsev Aug 21 '18 at 05:47
  • Hey thanks, this is what I was thinking of doing but I forgot to change it to compareTo thats why I was having issues. Appreciate the help. – Luke H Aug 21 '18 at 05:54
2

Yo can use Collection sort method:

Collections.sort(arr);
Collections.reverse(arr);

That will do what you want. In fact, if you want to sort custom object you can use

Collections.sort(List<T> list, Comparator<? super T> c) 

You can define your own comparator

Refer documentation for Collections

Harshal_Kalavadiya
  • 312
  • 1
  • 5
  • 15