I am fairly new to C and programming in general, and I have a question about looping in the following bubble sort function:
void sort(int values[], int n);
{
int c, d, t;
for (c = 0; c < (n - 1); c++)
{
for (d = 0; d < c - n - 1; d++)
{
if (values[d] > values[d + 1])
{
t = values[d];
values[d] = values[d + 1];
values[d + 1] = t;
}
}
}
}
The part that I'm specifically trying to understand is the second for loop:
for (d = 0; d < c - n - 1; d++)
I understand that the function is iterating through the array each time, comparing side-by-side values up until the last sorted element and bubbling the biggest element to the end of the array; however, I cannot seem to wrap my head around the meaning of:
while d < c - n - 1;
and how it translates. When I play this out in my mind I'm imagining that on the first time looping, d < c - n - 1 equates to 0 < 0 - 10 - 1. It seems to me that since c is always going to be less than n - 1, subtracting n - 1 from c will always result in a value less than 0, and d is never less than 0 so should never execute. I know that I'm just looking at this wrong and will probably have a 'duh' moment when the answer is presented, but this is bothering me.
If I put the first for loop into words, it says: while c is less than the length of the array, execute the contents of this loop then increment c. Can someone put the second for loop into words in a similar way, explaining the meaning of d < c - n - 1?