Selection Sort in Java produces incorrect results

You are almost there.

The part that swaps elements should be outside the inner loop.

In other words, you need to first find the smallest element in the remainder of the array, and then swap it into the current position. Right now you're swapping as soon as you have found a smaller number, and in the process failing to keep track of the new position of this smaller number.

Another way to fix the code is to keep the swap where it is, but update min after each swap:

if (min !=i) {
    int temp = a[i];
    a[i] = a[min];
    a[min]= temp;
    min = i;       /* Update `min' to reflect the number's new position */
}

This too will work, but is rather inefficient.

P.S. The if (min != i) check is unnecessary since swapping an element with itself is a harmless no-op.


You are swapping the elements for each iteration of inner loop Put the below block outside the inner loop. You should swap only for each iteration of outer loop.

         if (min !=i) {
                int temp = a[i];
                a[i] = a[min];
                a[min]= temp;
            }