someone has an idea how can I do that ?
thanks
If you need to do something to each element of a set of n
elements, you cannot do it with better than O(n
) performance.
If you mean "initialize a dense array of N items in a time independent of N", then it is physically impossible. A dense array has a storage space that grows linearly with the number of items, and it will take a linear amount of time to initialize this space.
You can have constant-time initialization using a sparse array. That is essentially an associative array (or hashmap, or dictionary, or table, depending on the language) which initializes items when they are first accessed.
I think its just a simple syntax question. In C++ you can do this:
int foo[1000] = {0};
All values in array are now 0
While it looks like its done in constant time, it still O(n)
You can initialize an array in O(1) worst-time and O(1) extra space, and it can be improved to using only 1 extra bit of memory.
Both can be found in this Paper, explained simply in this Article, and implemented in the Farray project.
Full disclosure - the last two were written by me.
It is the state-of-the-art Initializable array, and will probably stay that. The above paper proves that without the extra bit - the fill (init) operation should take Ө(n) time, even for amortized/randomized algorithms.
Actually, it is possible, but only with hardware help. On software, you will have to do a number of steps proportional to n
, thus it is O(n)
; on hardware, however, you can wire things so that all elements of the array are set in parallel.
This is in fact a time/space tradeoff; while before one needed O(n)
time, now one needs O(n)
circuit elements but can do the operation in O(1)
time.
And it is actually a common thing to do. A lot of hardware has a reset input which, when asserted, sets the whole hardware to a known state. This can involve for instance zeroing the whole memory.
you can initialize an array with a constant value in O(1) time. but it requires extra memory.
have a look at Initializing an array in constant time
You can do it in O(1), if you calculate the runtime with an Amortized Analysis over all future read actions. You just have to initialize your element on demand (the first time its read).
No. It's physically impossible. However, you can use vector instructions to make it some O(n * 1/k) time, where k is the width of a vector setter instruction. That's still O(n), but the constant is shrunk.