Question understanding casted loop
Hello i got a problem in my code i did a bubble sort but i did it after trying some stuff i didnt understand what i wrote anyways i will post my code then i will ask my question
Code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define NUM 10
void put_random(int *array)
{
int i;
for(i=0;i<10;i++)
array[i]=rand( ) % NUM;
}
void sort_it(int *array)
{
int i,x;
for(i=0;i<NUM;i++) {
for(x=0;x<NUM;x++) {
if(array[x]>array[x+1]){
int buffer;
buffer=array[x+1];
array[x+1]=array[x];
array[x]=buffer;
}
}
}
}
int main(void)
{
int array[10];
int i;
srand(time(NULL));
put_random(array);
puts("array before sorting\n");
for(i=0;i<10;i++)
printf("%d ",array[i]);
puts("\n");
sort_it(array);
puts("Now after\n");
for(i=0;i<10;i++)
printf("%d ",array[i]);
getchar();
return 0;
}
lets say we have in this 3 ints:
in double for loop it will check like for example x if we did 3 nums it will check the num 3 times
so in this example in the sort function downstairs for example in the check we will check array[x] > array[x+1]
then we do a buffer to save in the x+1 then we switch x+1 =array[x] so for example we have 3,2,1
so it will check first 3 3 times right ? like for example:
buffer=2;
array[x+1]=3;
array[x]=2;
so now will be like this 2,3,1
now it will check again the 2
is 2 > 3 no its not dont do anything now
is 2 > 1 yes do now
now it will be buffer[x+1] whish is 3 not 1 so how could it now be be fixed?
does the casted for loop check the 3 with all numbers or how does it would it work..
i know this is noob question but there some stuff in c i dont know how they operate even after doing c for
2 month now but i wanna understand it so i dont be like those ppl who does code and dont understand what
happens inside thanks.