Hi. I'm trying to learn C (no prior programming experience) and came across this bubble sort example:
To me it appears that the first time the if-statement in the inner for-loop runs...
"if (nums[inner] < nums[outer])"
...the same two array elements are compared, because outer is assigned to inner in the inner for-loop start expression.
That doesn't make sense to me, but being a rookie I'm aware that I'm missing something. Can someone explain to me why I'm wrong or why this is done?
“ // Sort the array
for (outer = 0; outer < 9; outer++)
{
didSwap = 0; //Becomes 1 (true) if list is not yet ordered
for (inner = outer; inner < 10; inner++)
{
if (nums[inner] < nums[outer])
{
temp = nums[inner];
nums[inner] = nums[outer];
nums[outer] = temp;
didSwap = 1;
}
}
if (didSwap == 0)
{
break;
}
}
// Now list the array as it currently is after sorting
puts("\nHere is the list after the sort:");
for (ctr = 0; ctr < 10; ctr++)
{
printf("%d\n", nums[ctr]);
}
return(0);
}”
Excerpt From: Dean Miller. “C Programming Absolute Beginner's Guide, 3/e.” iBooks.
https://itun.es/dk/mgpUO.l