void insertion_sort(int *a, int n)
{
int 
for(i=1;i<n;i++)
{
value=a[i];
for(j=i;j>0 && value<a[j-1];j--)
a[j]=a[j-1];

a[j]=value;
}
}



can anyone pls explain me the flow of this code... i am having confusion in understanding the flow..

Recommended Answers

All 4 Replies

Do small array, say four elements and write to paper changed values after each line of code.

can you tell me that after the control executes this line

a[j]=a[j-1];

where will the control go after that?
will it go for j-- or for

a[j]=value;

j>0 && value<a[j-1]

That statement is part of first for executed in this condition and repeating j-- at end of each loop.
a[j] = value is only excecuted after the loop finishes.

Formatted in Astyle in Code::Blocks

void insertion_sort(int *a, int n)
{
    int
    for(i=1; i<n; i++)
    {
        value=a[i];
        for(j=i; j>0 && value<a[j-1]; j--)
            a[j]=a[j-1];

        a[j]=value;
    }
}
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.