Search code examples
javaarraysalgorithmsortingselection-sort

Selection sort algorithm problems


So I have this code for my selection sort:

public static void selectionSort(int[] arrayToSort){
    int smallest;
    for(int i = 0; i < arrayToSort.length; i++){
        smallest = i;
        for(int j = i+1; j < arrayToSort.length; j++){
            if(arrayToSort[j] < arrayToSort[smallest]){
                smallest = j;
            }
            if(smallest != i){
                int temp = arrayToSort[i];
                arrayToSort[i] = arrayToSort[smallest];
                arrayToSort[smallest] = temp;
            }
        }
    }
}

I am generating a int array with random numbers. My selection sort sometimes does sort the array, sometimes it does "almost" sort the array. The array will mostly be sorted except for a very few numbers which are in wrong places. I can't figure out what goes wrong here, any ideas?

Some test results where the array were not completely sorted:

***NON SORTED***
77
53
27
58
83
***SORTED***
27
53
77
58
83

and

***NON SORTED***
40
87
27
48
82
***SORTED***
27
40
82
48
87

Solution

  • You have a part of code inside the inner loop, put it outside the loop;

    public static void selectionSort(int[] arrayToSort){
        int smallest;
        for(int i = 0; i < arrayToSort.length; i++){
            smallest = i;
            for(int j = i+1; j < arrayToSort.length; j++){
                if(arrayToSort[j] < arrayToSort[smallest]){
                    smallest = j;
                }
            }
            if(smallest != i){
                int temp = arrayToSort[i];
                arrayToSort[i] = arrayToSort[smallest];
                arrayToSort[smallest] = temp;
            }
        }
    }
    

    See for instance the algorithm in Wikipedia.