Search code examples
cinsertion-sort

insertion sort in c , need correction


I am trying to create an insertion sort in C. We used the following code in school, but it's not working.

    #include <stdio.h>
    #include <conio.h>

    int main(int argc, char const *argv[])
    {
        int a[6] = {5,8,3,2,9,1};
        int i,j, key;
        int countArraySize = sizeof(a)/sizeof(int);


        for (i = 0; i < countArraySize; ++i)
        {
            key = a[i];
            j = i - 1;

            while( j>=0 && key < a[j]) {
                a[j+1] = a[j];
                j--;
            }

            a[j+1] = key;
            printf("%d\n", a[j+1]);
        }


        return 0;
    }

Thanks.


Solution

  • The sort is correct but you are simply printing out the wrong thing. You should not be printing out during the sort. As it is, the code just prints out each key as it is encountered in the input. Instead, the printing should be done after the sort has completed. That is, remove the printf from within the current for loop and put it into a seperate for loop after the sorting has completed:

    for (i = 0; i < countArraySize; ++i) {
        key = a[i];
        j = i - 1;
    
        while( j>=0 && key < a[j]) {
            a[j+1] = a[j];
            j--;
        }
    
        a[j+1] = key;
    
        /* FOLLOWING LINE REMOVED */
        /* printf("%d\n", a[j+1]); */
    }
    
    /* ADDED THIS BLOCK TO PRINT THE SORTED ARRAY */
    for (i = 0; i < countArraySize; ++i) {
         printf("%d\n", a[i]);
    }