Hi, I was learning insertion sort in C. But I need help to clear up my confusion in the following code:

    int i,j,n; puts("Enter the number of elements: ");
    scanf("%d",&n);
    int A[n];
    readarr(A,n);
    int sortedA[n];
    sortedA[0]=A[0];
    for(i=1;i<n;++i)
    {
        j=i-1;
        while(j>=0 && sortedA[j]>A[i])
        {
            sortedA[j+1]=sortedA[j]; /*marked line 1*/
            --j;
        }
        sortedA[j+1]=A[i]; /*marked line 2*/
    }

In the marked line 1, you see that value at position [j] has been moved down in the list to [j+1], so that the position [j] is now vacant. Right?
Then, in marked line 2, why has A[i] been assigned to position [j+1]? Because, according to me, it should go to position [j].
While this method runs successfully, mine does'nt! Why? I really can't figure out what is happening here! Let me know what I don't!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.