Search code examples
calgorithmsortingselection-sort

Have I written the Selection Sort Algoithm in C the right way?


A question in my book explained selection sort in three lines and then asked the reader to write CODE for it in C. I have written the code here and it is working fine, but I am a little confused whether I have written it in the right way or not. Please read the code, I have even added comments and correct me if needed.

    #include <stdio.h>

    #define VALUESIZE 10

    int main(void)
    {
        int temp;
        int value[VALUESIZE] = {3, 5, 46, 89, 72, 42, 312, 465812, 758, 1};

// Printing array just for the user to see.
        for (int k=0; k<VALUESIZE; k++)
        {
        printf("[");
        printf("%d", value[k]);
        printf("] ");
        }
        printf("\n");

// Sorting algo begins
for (int i=0; i < VALUESIZE - 1; i++) // This will obviously loop through each element in our array except the last element as it will automatically be sorted after n-1 steps
{
    for (int j= i+1; j <= VALUESIZE; j++) // This nested loop will go through each element which appears after ith element. For e.g. If i = 2, then j will loop through entire array starting from j = 3
    {
        if (value[i] > value[j])  // This basic if statement will compare our ith and following jth value
        {
            temp = value[i];      // If the program finds any value[j] greater than value[i], then the values will be swapped.
            value[i] = value[j];
            value[j]  = temp;
        }
    }
}
// Now after sorting, print the new sorted array.
for (int l=0; l<VALUESIZE; l++)
{
    printf("[");
    printf("%d", value[l]);
    printf("] ");
}
printf("\n");

}


Solution

  • Select sort needs to iterate through the array to compare the ith value. At the end of this pass it will swap the 2 values. This is a reason why its not a very good sort algorithm for medium or large arrays.

    I have changed your code a bit below

    Untested but should work:

    // Sorting algo begins
    for (int i = 0; i < arr_length - 1; i++)
    {
        int min = i;
        for (int j = i + 1; j <= arr_length; j++) 
        {
            if (value[j] < value[min])
            {
                min = j;
            }
        }
        //now swap
        int cache = value[min];
        value[min] = value[i];
        value[i] = cache;
    }