In: Computer Science
(Sort ArrayList) Write the following method that sorts an ArrayList:
public static <E extends Comparable<E>>
void sort(ArrayList<E> list)
Write a program to test the method with three different arrays:
Integers: 2, 4, and 3;
Doubles: 3.4, 1.2, and -12.3;
Strings: "Bob", "Alice", "Ted", and "Carol"
This program is similar to the Case Study in the book: Sorting an Array of Objects
the language is in java
Code:
public static <E extends Comparable<E>> void
sort(ArrayList<E> list) {
//read all the values from the list
one by one and in inner loop compare with other elements in the
list
for (int i = 0; i < list.size() - 1; i++) {
E MinValue = list.get(i); //creates minimum value based for the
selected type of variable
int min = i; // store the index into an integer variable assigned
aboev,which we use to swap in next steps
//inner oop to
compare
for (int j = i + 1; j < list.size(); j++) {
//if the number is less than the selected then
change the imin value to least value ,i.e swap values if list(j) is
less than list(i)
if (list.get(j).compareTo(MinValue) < 0) {
MinValue = list.get(j);
min = j;
}
}
//after
comparing the list elements,set the values
if (min != i) {
list.set(min, list.get(i));
list.set(i, MinValue);
}
}
}
O/P:
Doubles:
Strings: