So, why won't this code work it is returning the original list always (I haven't put the return statement, but can someone determine why the logic behind my selection sort algorithm is not working). Any help would be gladly appreciated!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayListDemo {
public static void main(String [] args) {
ArrayList <String> list = new ArrayList <String> (15);
list.add("Wilson");
list.add("Annans");
list.add("Manning");
list.add("Branday");
list.add("Smittens");
list.add(2, "Goddard Fey");
list.set((list.size()) - 1, "Brand Brandon");
list.add("Brand Boarders");
selectionSort(list);
}
static void selectionSort(ArrayList<String> a) {
int smallindex;
for(int i = 0; i < a.size(); i++) {
smallindex = i; // set first element as smallest
for(int j = i + 1; j < a.size(); j++) { // find smallest
if (a.get(j).compareTo(a.get(smallindex)) > 0) {
swap(a, i, j);
}
}
}
}
static void swap(ArrayList<String> a, int index1, int index2) {
String i_string = a.get(index1);
String j_string = a.get(index2);
String temp = i_string;
i_string = j_string;
j_string = temp;
}
}
swapmethod does not modify theArrayLista anywhere. You need something likea.set(index1, i_string)etc.