I'm trying to sort the elements in the array list based on the length of the words in the list. so the shortest to the longest. With the code below, it won't get sorted for some reason.
Question - Where is the bug in my implementation?
public static void sort(ArrayList<String> list) {
for(int i = 0; i < list.size(); i++) {
String e1 = list.get(i);
for(int j = i; j < list.size(); j++) {
String e2 = list.get(j);
if( e1.length() > e2.length()) {
String tmp = e1;
e1 = e2;
e2 = tmp;
}
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
Edit:
public static void sort(ArrayList<String> list) {
for(int i = 0; i < list.size(); i++) {
String e1 = list.get(i);
for(int j = i; j < list.size(); j++) {
String e2 = list.get(j);
if( e1.length() > e2.length()) {
String tmp = e1;
e1 = e2;
e2 = tmp;
list.set(j, e1);
list.set(i, e2);
}
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}