is it possible to call a rand() to generate number in ascending order or descending order without sorting it externally? i mean the generated number itself already in ascending or descending order?
meaning comparison between array of numbers must be done. is it possible to have 1 call then the numbers are already in ascending order? i mean like doing some coding.
You don't need to compare with all the number you already have, just the last one
example:
random number = 5
keep 5 as it's the 1st number you get
random number = 8
8 > 5 so keep 8
random number 7
7 < 8 so get another number
random number = 10
10 > 8 so keep 10 (10 > 8 > 5 for sure so you don't need to check it)
what i mean is let's say i wanna generate 100 data within the range 0-200. then, i hope the RNG will generate the data in ascending order or descending order without the need of sorting coding to sort the data.
Grey Wolf, what is priority_queue?
besides, i hope to save the generated data in an array.
p/s: actually i am doing an assignment to sort data in best,average and worst cases. when i generate the data, i need to sort it first before sorting it again for best case and worst case. it seems not very practical.
Priority queues[1] are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains.
#include <iostream>
#include <queue>
#include <ctime>
usingnamespace std;
int main()
{
srand((unsigned)time(0));
constint arraySize = 20;
constint upperBounds = 200;
int orderedRandArray[arraySize] = {0};
//
// Generate and sort the random numbers
priority_queue<int> orderedRand;
for (int i = 0; i < arraySize; ++i)
{
orderedRand.push( rand() % upperBounds);
}
//
// Get the numbers out of the queue and store them.
for(int i =0; i < arraySize; ++i)
{
orderedRandArray[i] = orderedRand.top();
orderedRand.pop();
//
// Show number on screen.
cout << orderedRandArray[i] << endl;
}
return 0;
}
EDIT:
I've just noticed your PS, It sounds like you should be writing the sort code yourself and comparaing different sorting algorithms.[2]