Say I am generating random numbers using Math.random()
, maybe 1000 of them, and I want to have them in ascending order (at all times). Is there an algorithm of some variety that can keep them sorted the whole time, without ever having to call a sort routine? The only thing I can think of is a BST? but there might be a better way.
Some code will help:
const numContainer = {};
for(let i = 0; i < 1000; i++){
const r = Math.random(); // I generate a new RV
numContainer[r] = {r}; // I want to store it in order, but this isn't helping :-)
}
clearly the above is not really going to maintain any numerical order for the keys etc. I am looking to have them be sorted as I go.
Update 1: I realize the use-case might be good to know (or interesting). The use-case is a discrete-event-simulation, the smaller the random uniform variable the sooner the event, so I need to read the events in numerical order so it would be nice if they were sorted, naturally, instead of requiring a sort or what not.
Update 2: I realized binary search (with an array), won't really be much good since I will have to insert the new item and that insert will end up being O(n), so back to square one. So my guess is just some sort algorithm that works with an already sorted array, will be fastest?