Michael Lilley Michael Lilley - 7 months ago 18
Java Question

Why is my selection sort sorting the array out of order?

This is part of my program:

private static int[] array = {5, 2, 3, 1, 4, 7, 8, 6, 10, 9};

private static void selectionSort(int arr[])
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[index])
{
index = j;
}

int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]);
}
}


I'm trying to sort all of the numbers in order. It is printing the following:

1 3 2 5 4 6 7 8 9 10


I don't understand why some numbers are in order, and others aren't. Can anyone be of assistance?

Answer

You should be comparing arr[j] with arr[index] (not arr[i]) and you shouldn't swap the elements until your inner loop completes. And you can use Arrays.toString(int[]) to print your array. Something like,

private static void selectionSort(int arr[]) {
    for (int i = 0; i < arr.length - 1; i++) {
        int index = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[index]) {
                index = j;
            }
        }
        if (index != i) {
            int smallerNumber = arr[index];
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }
    }
}

public static void main(String[] args) {
    int[] array = { 5, 2, 3, 1, 4, 7, 8, 6, 10, 9 };
    selectionSort(array);
    System.out.println(Arrays.toString(array));
}

Output is (as expected)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]