Suppose we start with some array of indices. I want some function
int* getOrdering(int* idxs, int len);
which is equivalent to this process (in pseudocode):
input: int* idxs, int len
std::vector<int> a = {1,2,...,len+1};
out = {0,...,0}; // empty initialized array with length len
n = 0;
while n < len:
out[n] = a[idx[n]]; // first iteration sets out[0] to a[idxs[0]] = 4.
a.erase(a.begin() + n);
++n;
For getOrdering({3,0,0,2,0}, 5)
:
n |
idx[n] |
a |
out |
---|---|---|---|
0 |
3 |
{1,2,3,4,5,6} |
{4} |
1 |
0 |
{1,2,3,5,6} |
{4,1} |
2 |
0 |
{2,3,5,6} |
{4,1,2} |
3 |
2 |
{3,5,6} |
{4,1,2,6} |
4 |
0 |
{3,5} |
{4,1,2,6,3} |
I was wondering if anyone has a better algorithm than this for finding this ordering, because my application will be running this in the order of O(len!)
times. We can always assume the indices input are are always correct and will never result in error, i.e. idx[n]
is always in the range [0,len-n)
.
Further, does the vector erase operate in O(1)
? If not, is there a better data structure to use to keep this process to O(1)
?