run this
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
// use smaller numbers to see what is going on
int main()
{
int i;
int array[3] = { };
int j;
int randNum, num = 3, size;
int temp;
srand((int)time(0)); // Seeds Random Numbers
size = sizeof(array)/sizeof(array[0]);
printf("size = %d\n", size);
for (i = 0; i < num ; i++) // Will go through as long as i < 100, i=i+1 every iteration starting at 0.
{
randNum = rand() %15; // Gets 100 random integers on the interval [1,20]
array[i] = randNum; // Assigning each of the generated random ints to the array myArray[i]
}
for (i = 0; i < ( num - 1 ); i++) {
for (j = 0; j < num - i - 1; j++) {
printf("array[j]%d > array[j+1]%d\n",array[j] , array[j+1] );
//if first number greater than second number hold it else where.
if (array[j] > array[j+1])
{
//here
temp = array[j];
// move the smaller one where the bigger one was.
array[j] = array[j+1];
printf(" array[j] %d = array[j+1] %d\n", array[j] , array[j+1]);
array[j+1] = temp;
// put the greater one where the smaller one was
// keep moving next time around the same two will no longer
// evalute to 3 > 1, but will be 1 > 3 = no move to the next one.
}
}
}
for(i=0; i<num ; i++)
{
printf("Element: %d\n", array[i]);
}
return 0;
}
oh yes, remember
Code:
int j = 3;
array[j] <--- j sets the element number not value inside of it;
// so array[ j + 1] == what?
if j = 3 , then it is looking into element number 2 : 0,1,2,3,4
so j + 1 then is looking into element number 3 : 0,1,2,3,4
which is one ahead of j.
Code:
array [2] = 3;
array[3] = 1;
3 > 1
if ( array[j] > array [ j + 1])
// you have to hold that value in a temp so it does not get lost when you over write its place setter/keeper.
3 = 3
temp = array[j];
now move the lesser 1 to the "left"
< -- 1
array[j] = array[j+1];
then put the greater 3 in the lesser place.
< ---3
array[j+1] = temp;
ending up with
array[j]=1 or array [ 2 ] = 1
array[j+1] = 3 or array [ 3 ] = 3
or
1,3