Since this year I'm starting studying C programming at university. In particular today I was trying to understand the insertion sort. I wrote this code that is perfectly working:
void insertionSort (int v[], int s)
{
int i;
int j;
int value;
for (i = 1; i < s; i++)
{
value = v[i];
for (j = i - 1; (j >= 0) && (value < v[j]); j --)
{
v[j + 1] = v[j];
}
v[j + 1] = value; // why v[j+1]?
}
}
My question is about the last code line: v[j + 1] = value
. If I understand correctly, j
(that decreases every time), at the end of the for
cycle, has a value of -1 and that's why is correct to write v[j + 1] = value
.
Am I right or am I missing something? Really thanks for anybody who wants to help me by explaining me better.