Search code examples
javaselection-sort

Java: Selection Sort My implementation vs. another


The following is my implementation of Selection Sort:

package algorithm.selectionsort;

public class SelectionSort {

    public static void main(String[] args) {
        int[] myArray = selectionSort(new int[] { 9, 9, 9, 8, 7, 73, 32, 109, 1100, 432, 321, 0 });

        for (int element : myArray) {
            System.out.print("" + element + " ");
        }

    }

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

                }
            }
        }
        return a;

    }

}

I noticed that my instructor codes it slightly differently:

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


            }
        }
        int temp = a[i];
        a[i] = a[min];
        a[min] = temp;
    }
    return a;

}

Both implementations work. I'm curious as to what the difference here is. Is it efficiency?


Solution

  • The difference between your instructor's and yours is that he iterate through the array and for each element, search for the minimum, then perform a swap with the element after the wall index.

    For yours, you iterate through the array and for each element, while searching for the minimum, if current value is < then the current tentative min, perform a swap with the element after the wall index.

    So instead of swapping n times, you could possible swap n*n times for worst case:

    Your swap for just one pass (worst case):

    100, 90, 88, 70, 55, 43, 32, 28, 19, 10
    90, 100, 88, 70, 55, 43, 32, 28, 19, 10
    88, 100, 90, 70, 55, 43, 32, 28, 19, 10
    70, 100, 90, 88, 55, 43, 32, 28, 19, 10
    55, 100, 90, 88, 70, 43, 32, 28, 19, 10
    43, 100, 90, 88, 70, 55, 32, 28, 19, 10
    32, 100, 90, 88, 70, 55, 43, 28, 19, 10
    28, 100, 90, 88, 70, 55, 43, 32, 19, 10
    19, 100, 90, 88, 70, 55, 43, 32, 28, 10
    10, 100, 90, 88, 70, 55, 43, 32, 28, 19
    

    Your instructor's swap for just one pass (worst case):

    100, 90, 88, 70, 55, 43, 32, 28, 19, 10
    10, 90, 88, 70, 55, 43, 32, 28, 19, 100
    

    In essence, you swap the values while in the midst of searching for the min. The "min" you swapped may not be the lowest value in the array.