I am trying to learn the bubble sort algorithm in a book for C. I can't seem to understand in the code below how int outer and int inner link to which element of the nums array. Like how does inner become nums[0] while outer becomes nums[1] (if I'm correct), then progresses through the loop?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int ctr, inner, outer, didSwap, temp;
int nums[10];
time_t t;
srand(time(&t));
for (ctr = 0; ctr < 10; ctr++)
{
nums[ctr] = (rand() % 99) + 1;
}
puts("\n Here is the list before the sort: ");
for (ctr = 0; ctr < 10; ctr++)
{
printf("%i\n", nums[ctr]);
}
for (outer = 0; outer < 9; outer++)
{
didSwap = 0;
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;
}
}
puts("\n Here is the list after the sort: ");
for ( ctr = 0; ctr < 10; ctr++)
{
printf("%i\n", nums[ctr]);
}
return 0;
}
inner never becomes nums[0]. inner and outer are array indexes, so when inner is 0, nums[inner] is nums[0].
The code that performs the comparison and swapping never does that with inner and outer, it uses nums[inner] and nums[outer].
if (nums[inner] < nums[outer])
{
temp = nums[inner];
nums[inner] = nums[outer];
nums[outer] = temp;
didSwap = 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With