Insertion sorting algorithm in C

I have a question about the following code for Insertion Sort:

void insertion(Item a[], int ell, int r)                
{               
    int i;          
        for (i=ell+1; i<=r; i++)            
           compexch(a[ell], a[i]);          
    {           
        for (i=ell+2; i<=r; i++)        
        {       
            int j=i;    
            Item v=a[i];    
            while(less (v, a[j-1])) 
            {   
                a[j]=a[j-1];
                j--;
            }   
            a[j]=v;
        }       

    }           
}

Ok, so my question specifically deals with the while while part. I see that j is decrementing and wants to know what happens when j = 0 and a [-1] happens. I don’t understand how we can resolve a negative index - what if the information we compare is triggered and the while loops continue to work? Thank you

+4
source share
1 answer

, compexch(x,y) - if (less(y,x)) { Item t = x; x=y; y=t }. , , for, a[ell] Item a[ell+1],...,a[r]. j i, ell+2, j > ell while. while , , , j == ell. a[ell] , less(v, a[ell]) false, .

, j ell.

+1

Source: https://habr.com/ru/post/1625593/


All Articles