Jan 19, 2021 at 6:36am UTC
Hi C++ ;
I have 5 random arr; how can I sort this 5 random numbers
from less to high ?
Thanks;
1 2 3 4 5 6 7 8 9 10 11
int n[4];
for (int i = 1; i < 6; i++)
{
cout << " line " << i + 1 << " : " ;
cout << n[0] + (rand() % 15) << " " ;
cout << n[1] + (rand() % 15) << " " ;
cout << n[2] + (rand() % 15) << " " ;
cout << n[3] + (rand() % 15) << " " ;
cout << n[4] + (rand() % 15) << " " << endl;
}
Last edited on Jan 19, 2021 at 6:37am UTC
Jan 19, 2021 at 8:37am UTC
Second, your have to actually store the random numbers in the array before you can sort it.
Lines 6-9: You appear to be printing uninitialized members of the array.
Line 10: As salem c pointed out, n[4] is out of bounds.
Jan 19, 2021 at 8:21pm UTC
the idiotic lazy way (a specialty of mine, I think 2 of my professors retired right after I was in their class).
something like...
int n[5];
n[0] = rand() % maxval*0.2;
n[1] = n[0] + rand()%maxval*0.2;
n[2] = n[1] + ... etc
yes, its blatant cheating. Sometimes, depending on the true requirement, blatant cheating is the correct solution. Other times, it really isnt. But its "an" answer. You eliminate the need to sort by generating them in assured sorted order. if the quality of the randomness is not important, its good enough for many a problem.
Last edited on Jan 19, 2021 at 8:24pm UTC