im pretty new to programming an this solution has me stumped...the program generates 15 random numbers(between 0 and 999) and is supposed to display them in sorted order(ascending), i know it works, i just don't know HOW it displays the values in sorted order using the 2 nested loops, heres the main function:
int main()
{
const int NUM_VALS = 15;
int values[NUM_VALS];
int current;
srand(time(0));
for (int i = 0; i < NUM_VALS; i++)
{
nextVal = rand() % 1000;
current = 0;
while (current < i && nextVal >= values[current]) //heres where im lost
current++;
for( int j = i; j > current; j--)
values[j] = values[j-1];
values[current] = nextVal;
}
for (int i = 0; i < NUM_VALS; i++)
{
nextVal = rand() % 1000; //Generate the next number
current = 0; //Assume it should be at position 0
while (current < i && nextVal >= values[current]) //If it is greater than the value at current position
current++; //move to the next position
for( int j = i; j > current; j--) //Move all the numbers above it up
values[j] = values[j-1]; //by 1 to make space
values[current] = nextVal; //insert at the position found for it.
}
Where you have a short piece of code like this, and want to figure out how it works then pencil & paper can be a good tool.
You can simplify it to just 5 numbers, for example, and use the birthday of a few friends as a way to get some 'random' numbers.
If you work through how the code will handle that it should make understanding it easier.