Search code examples
javaarraylistselection-sort

Java ArrayList String Selection Sort


I'm struggling mightly on doing selection sort on an ArrayList of Strings to alphabetize them. I have no idea what I'm doing wrong. But its just not working properly for me. Heres my code.

    ArrayList<String> list = new ArrayList<String>();
    list.add("a");
    list.add("d");
    list.add("f");
    list.add("c");
    System.out.println(list);
    int i;
    int j;
    int minValue;
    int minIndex;

    for (i=0; i<list.size(); i++) {
        System.out.println(list.get(i));
        char iLetter = (list.get(i).charAt(0));
        int iValue = (int) iLetter;
        minValue = iValue;
        minIndex = i;
        for(j=i; j<list.size(); j++) {
            char jLetter = list.get(j).charAt(0);
            int jValue = (int) jLetter;
            if (jValue < minValue) {
                minValue = jValue;
                minIndex = j;
            }
        }
        if(minValue < iValue) {
            int temp = iValue;
            char idx = list.get(minIndex).charAt(0);
            int idxValue = (int) idx;
            iValue = idxValue;
            idxValue = temp;

        }
    }
    System.out.println(list);
}

It still prints it out as ["a", "d", "f", "c"]


Solution

  • You are not updating your list anywhere in your loop, so it remains unsorted.

    In order to actually swap elements of the list, replace:

    if(minValue < iValue) {
        int temp = iValue;
        char idx = list.get(minIndex).charAt(0);
        int idxValue = (int) idx;
        iValue = idxValue;
        idxValue = temp;
    }
    

    with:

    if(minValue < iValue) {
        Collections.swap (list, i, minIndex);
    }
    

    Collections.swap performs the following modification:

    list.set(i, list.set(minIndex, list.get(i)));
    

    Now the output will be

    [a, c, d, f]