Search code examples
javaarrayssortingselection-sort

trying to implement selection sort but it wont work


i'm currently working on a project where I implement different types of sorting methods to sort an array. I got this implementation from my class but for some reason it is not working. I'm not sure where its going wrong and any help would be greatly appreciated.

public static void selectionSort(int[] a) {
    int n = a.length;
    System.out.println(n);
    for (int i = 0; i < n - 1; i++) {
        int min = i;
        for (int j = i + 1; j < n; j++) {
            if (a[j] < a[min]) {
                int swap = a[i];
                a[i] = a[min];
                a[min] = swap;
            }
        }
    }
}

The Algorithm: Finds the minimum value in the list. Swaps it with the value in the first position. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time). It divides the list into two parts. The sublistof items already sorted. The sublistof items remaining to be sorted.

input

int[] a = new int[]{-2, 4, 8, 1, 9, -6};

expected output

-6, -2, 1, 4, 8, 9

Solution

  • You're missing a crucial step to update the minimum index here. Have a look at if block in below code.

    public static void selectionSort(int[] a) {
        int n = a.length;
        for (int i = 0; i < n - 1; i++) {
            int min = i;
            for (int j = i + 1; j < n; j++) {
                if (a[j] < a[min]) {
                    min = j;
                    int swap = a[i];
                    a[i] = a[min];
                    a[min] = swap;
                }
            }
        }
    }