Search code examples
javaarraysselectionsorting

Modified selection sort that selects the biggest number


I am trying to write a modified selection sort that selects the biggest number and place it at the end of a list. I ran into a problem. The code is kind of sorting the list but not perfectly. This is the result after I ran the code: Before selection sort: [2, 8, 7, 1, 3, 5, 9, 4, 6] After selection sorted: [1, 2, 8, 7, 3, 4, 5, 9, 6]

Here is my code:

public static int[] sort(int[] list) {
int i, j, maxNum, maxInde, temp = 0;
    for (i = list.length-1; i >= 0; i--) {
        maxNum = list[i];
        maxInde = i;
        for (j = i; j < list.length; j++) {
            if (list[j] < maxNum) {
                maxNum = list[j];
                maxInde = j;
            }
        }
        if (maxNum < list[i]) {
            temp = list[i];
            list[i] = list[maxInde];
            list[maxInde] = temp;
        }
    }
    return list;
}  

I don't know where the issue is located.


Solution

  • Here is the fixed version:

    int i, j, maxNum, maxInde, temp = 0;
    for (i = list.length-1; i >= 0; i--) {
    // you start iterating from the end of the list 
    // which means that the elements between i and the end of the list are sorted
        maxNum = list[i];
        maxInde = i;
        for (j = 0; j < i; j++) { 
        // you have to iterate through the nonsorted elements
            if (list[j] > maxNum) {
                maxNum = list[j];
                maxInde = j;
            }
        }
        if (maxNum > list[i]) {
        // if you found an element that is bigger then the current element
        // then it should be set as the current element
            temp = list[i];
            list[i] = list[maxInde];
            list[maxInde] = temp;
        }
    }