import java.util.ArrayList; public class SelectionSort { // instance variables: private ArrayList names; // constructor public SelectionSort() { names = new ArrayList(); names.add("Alex"); names.add("Matt"); names.add("Logan"); names.add("Tomas"); names.add("Ian"); names.add("Sayuri"); names.add("Dan J"); names.add("Ben"); names.add("Sara"); names.add("Aidan"); names.add("Kaitlyn"); names.add("Kevin"); names.add("Dan O"); names.add("Nora"); names.add("Nick"); names.add("Paul"); names.add("Bailey"); names.add("Amrita"); names.add("Saahir"); names.add("Allie"); } public void sort() { int start = 0; String name, smallestSoFar, toSwap; int j, k, smallestPosition; // outside loop for (j = 0; j < names.size(); j++) { // assign the name at position j to 'toSwap' toSwap = names.get(j); // start by assuming that the name at position j is the 'smallest': smallestSoFar = names.get(j); smallestPosition = j; // inner loop // this is the part that steps through all the names and finds the "smallest" for (k = j + 1; k < names.size(); k++) { name = names.get(k); // a.compareTo(b) < 0 if a comes before b. It is > 0 if a comes after b. It is 0 if they're the same. int result = name.compareTo(smallestSoFar); // update 'smallestPosition' and 'smallestSoFar' if 'name' is smaller than 'smallestSoFar' if (result < 0) { smallestPosition = k; smallestSoFar = name; } } // Use a temporary variable 'temp' to swap 'smallestSoFar' with 'toSwap' String temp = names.get(smallestPosition); names.set(smallestPosition, toSwap); names.set(j, temp); } System.out.println("final result: " + names); } public static void main(String[] args) { SelectionSort s = new SelectionSort(); s.sort(); } }