1. (Sort ArrayList) Write the following method that sorts the elements of ArrayL
ID: 3791275 • Letter: 1
Question
1. (Sort ArrayList) Write the following method that sorts the elements of ArrayList in ascending order:
public static <E extends Comparable<E>> void sort(ArrayList<E> list)
import java.util.ArrayList;
public class Exercise19{
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(14);
list.add(24);
list.add(4);
list.add(42);
list.add(5);
Exercise19.<Integer>sort(list);
System.out.print(list);
}
/** Sort an array of comparable objects */
public static <E extends Comparable<E>> void sort(ArrayList<E> list) {
// Your code here!
}
}
}
Explanation / Answer
Exercise19.java
import java.util.ArrayList;
public class Exercise19{
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(14);
list.add(24);
list.add(4);
list.add(42);
list.add(5);
Exercise19.<Integer>sort(list);
System.out.print(list);
}
/** Sort an array of comparable objects */
public static <E extends Comparable<E>> void sort(ArrayList<E> list) {
// Your code here!
int n = list.size();
E temp ;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(list.get(j-1).compareTo(list.get(j)) > 0){
//swap the elements!
temp = list.get(j-1);
list.set(j-1,list.get(j));
list.set(j, temp);
}
}
}
}
}
Output:
[4, 5, 14, 24, 42]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.