Search code examples
carraysalgorithmsortinginsertion-sort

Output is showing different


#include<stdio.h>
int main()
{   
int a[6]={2,5,4,6,1,3};
int j,key,i,k;   
for(j=1;j<6;++j)
{
    key=a[j];
    i=j-1;
    while((i>=0)&&(a[i]>key))
    {
        a[i+i]=a[i];
        i=i-1;
    }
    a[i+1]=key;
}

for(i=0;i<6;i++)
printf("%d\n",a[i]);
}

When I calculate myself I get 1,2,3,4,5,6 but the output is 2,4,5,6,1,3.

I tried so hard, but couldn't find what is wrong in this.


Solution

  • There is a typo in your program.

    Instead of

    a[i+i]=a[i];
    

    there shall be

    a[i+1]=a[i];
    

    Take into account that according to the C Standard the function main without parameters shall be declared like

    int main( void )
    

    Also it is a bad idea to use "raw numbers" throughout the program.

    It is desirable to place the sorting into a separate function.

    The corresponding program can look like

    #include <stdio.h>
    
    void insertion_sort(int *a, size_t n)
    {
        for (size_t i = 1; i < n; i++)
        {
            size_t j = i;
            int value = a[i];
    
            for (; j != 0 && value < a[j - 1]; --j)
            {
                a[j] = a[j - 1];
            }
    
            if (j != i) a[j] = value;
        }
    }
    
    int main( void )
    {
        int a[] = { 2, 5, 4, 6, 1, 3 };
        const size_t N = sizeof(a) / sizeof(*a);
    
        for (size_t i = 0; i < N; i++)
        {
            printf("%2d ", a[i]);
        }
        putchar('\n');
    
        insertion_sort(a, N);
    
        for (size_t i = 0; i < N; i++)
        {
            printf("%2d ", a[i]);
        }
        putchar('\n');
    
        return 0;
    }
    

    Its output is

    2  5  4  6  1  3
    1  2  3  4  5  6
    

    For big arrays it is better to use the binary search instead of sequential comparisons.