views:

96

answers:

2

I'm writing a mobile phone based game in c. I'm interested in a data structure that supports fast (amortized O(1) if possible) insertion, look-up, and removal. The data structure will store integers from the domain [0, n] where n is known ahead of time (it's a constant) and n is relatively small (on the order of 100000).

So far I've considered an array of integers where the "ith" bit is set iff the "ith" integer is contained in the set (so a[0] is integers 0 through 31, a[1] is integers 32 through 63 etc).

Is there an easier way to do this in c?

+4  A: 

Your idea is simple and efficient - assuming you have 100000 / 8 = 12.5 KB to play with then I don't see any point in looking for other solutions.

Paul R
+1  A: 

A flat array would do, but would cost 100,000 bits. Another possibility is a "hash set".

ChrisW
100,000 bits is only 12.5 KB - unless he needs huge numbers of these bit sets then memory shouldn't be an issue ?
Paul R
@Paul R -- It's 100,000 bits independently of how many are set. If he's only setting a few, he may not want to spend that much. I'd agree that 12KB doesn't seem like much to me, even on a "mobile phone". If he needed several instances of this structure, though, then less would be better. In any case and for what it's worth, a hash set too is O(1).
ChrisW