Question:
I am trying to learn the bubble sort algorithm in a book for C. I can’t seem to understand in the code below howint 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
#include
#include
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; } [/code]
Answer:
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; } [/code]
If you have better answer, please add a comment about this, thank you!