I'm trying to follow through how the sort process is working though, here's the program :

#include <stdio.h> #define MAX 4 int a[MAX]; int rand_seed=170; /* from K&R - returns random number between 0 and 32767.*/ int rand() { rand_seed = rand_seed * 1103515245 +12345; return (unsigned int)(rand_seed / 65536) % 32768; } int main() { int i,t,x,y; /* fill array */ for (i=0; i < MAX; i++) { a[i]=rand(); printf("%d\n",a[i]); } /* bubble sort the array */ for (x=0; x < MAX-1; x++) { for (y=0; y < MAX-x-1; y++) if (a[y] > a[y+1]) { t=a[y]; a[y]=a[y+1]; a[y+1]=t; } } /* print sorted array */ printf("--------------------\n"); for (i=0; i < MAX; i++) printf("%d\n",a[i]); return 0; }

**Random numbers are :

11697 = a[0]

5078 = a[1]

31364 = a[2]

26294 = a[3]

So the sorting starts at line 29 - (to my understanding) the for loop with x will run 3 times.... x < 3(MAX-1)

0

1

2

then it hit's MAX-1(3) and will stop...

for every iteration of 'loop x' there is a nested loop with the variable y... this loop cuts off when y < MAX-x-1... which would allow it to run

0

1

2

When x is 0... Then when x = 1

0

1

So for every iteration of x loop y loop runs twice : 0, 1

Nested in y loop there is an if statement. This will be ran twice before reset(one for each iteration of y loop) and measures whether

a[0] > a[1] on the first iteration. And a[1] > a[2] on the second.

So if this program was run the first if statement would be working whether

a[y] 11697 > a[y+1] 5078

Which is true so we go into the if statement.

t = a[y]

So t = 11697

a[y] = a [y+1]

So a[0] = a[1] ---- a[0] = 5078

a[y+1] = t

So a[1] = 5078

Our array values have been effectively swapped. The random number array would now read

a[0] = 5078

a[1] = 11697

a[2] = 31364

a[3] = 26294

the next time the y loop runs the same process would be used, but the if statement would be checking if a[1] > a[2]

Which it isn't so the if statement doesn't run....

I'm not quite finishing it off though... I don't get how y ever references a[3] as it... ahh [y+1] stupid me

So this process runs for the second time, doing the same swap process to the array values a[1] and a[2]

a[1] is not greater than a[2], so the if statement doesn't execute...

On the last run of y a[2] is referenced against a[3], which is greater so they swap

a[0] = 5078

a[1] = 11697

a[2] = 26294

a[3] = 31364

X will now run again, but as the array's are in order the loops will exit.

Is this right? I think it works, but hopefully it show's any constructs that I'm not really communicating well, missed or don't seem to be understanding.