I'm as noobish as you get, first time using C and my first time programming. This is the 3rd program I am attempting to understand and replicate.
I understand that bubble sorting compares two values and swaps them if the larger value is in front.
However, with the following code, I just don't see how it happens when I try to "read" the code in plain English and write it out. I try to follow along with the numbers and do the math, but I don't get how the bubble sort is swapping anything. Can anyone explain just one full loop in English?
I've seen other codings where a "swap" code (function?) seems to be used, but I don't see that here. This code was found here: HowStuffWorks "How C Programming Works"
Code:
#include <stdio.h>
#define MAX 10
int a[MAX];
int rand_seed=10;
/* 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;
}
Thank you so much for even entertaining these noob questions. I will get better.