<p>I have an information retrieval application that creates bit arrays on the order of 10s of million bits. The number of "set" bits in the array varies widely, from all clear to all set. Currently, I'm using a straight-forward bit array (<code>java.util.BitSet</code>), so each of my bit arrays takes several megabytes.</p>

<p>My plan is to look at the cardinality of the first <em>N</em> bits, then make a decision about what data structure to use for the remainder. Clearly some data structures are better for very sparse bit arrays, and others when roughly half the bits are set (when most bits are set, I can use negation to treat it as a sparse set of zeroes). </p>

<ul>
<li>What structures might be good at each extreme? </li>
<li>Are there any in the middle?</li>
</ul>

<p>Here are a few constraints or hints:</p>

<ol>
<li>The bits are set only once, and in index order.</li>
<li>I need 100% accuracy, so something like a Bloom filter isn't good enough.</li>
<li>After the set is built, I need to be able to efficiently iterate over the "set" bits.</li>
<li>The bits are randomly distributed, so run-length&ndash;encoding algorithms aren't likely to be much better than a simple list of bit indexes.</li>
<li>I'm trying to optimize memory utilization, but speed still carries <em>some</em> weight.</li>
</ol>

<p>Something with an open source Java implementation is helpful, but not strictly necessary. I'm more interested in the fundamentals.</p>

[{'answer_id': 36311, 'author': 'Tall Jeff', 'author_id': 1553, 'author_profile': 'https://Stackoverflow.com/users/1553', 'pm_score': 5, 'selected': True, 'text': '<p>Unless the data is truly random <strong><em>and</em></strong> has a symmetric 1/0 distribution, then this simply becomes a lossless data compression problem and is very analogous to CCITT Group 3 compression used for black and white (i.e.: Binary) FAX images. CCITT Group 3 uses a Huffman Coding scheme. In the case of FAX they are using a fixed set of Huffman codes, but for a given data set, you can generate a specific set of codes for each data set to improve the compression ratio achieved. As long as you only need to access the bits sequentially, as you implied, this will be a pretty efficient approach. Random access would create some additional challenges, but you could probably generate a binary search tree index to various offset points in the array that would allow you to get close to the desired location and then walk in from there.</p>\n\n<p><strong><em>Note</em></strong>: The Huffman scheme still works well even if the data is random, as long as the 1/0 distribution is not perfectly even. That is, the less even the distribution, the better the compression ratio.</p>\n\n<p>Finally, if the bits are truly random with an even distribution, then, well, according to <em>Mr. Claude Shannon</em>, you are not going to be able to compress it any significant amount using any scheme.</p>\n'}, {'answer_id': 36738, 'author': 'Tim Ring', 'author_id': 3685, 'author_profile': 'https://Stackoverflow.com/users/3685', 'pm_score': 0, 'selected': False, 'text': '<p>Straight forward lossless compression is the way to go. To make it searchable you will have to compress relatively small blocks and create an index into an array of the blocks. This index can contain the bit offset of the starting bit in each block.</p>\n'}, {'answer_id': 36775, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 0, 'selected': False, 'text': '<p>Quick combinatoric proof that you can\'t really save much space:</p>\n\n<p>Suppose you have an arbitrary subset of n/2 bits set to 1 out of n total bits.  You have (n choose n/2) possibilities.  Using <a href="http://en.wikipedia.org/wiki/Stirling%27s_formula" rel="nofollow noreferrer">Stirling\'s formula</a>, this is roughly 2^n / sqrt(n) * sqrt(2/pi).  If every possibility is equally likely, then there\'s no way to give more likely choices shorter representations.  So we need log_2 (n choose n/2) bits, which is about n - (1/2)log(n) bits.</p>\n\n<p>That\'s not a very good savings of memory.  For example, if you\'re working with n=2^20 (1 meg), then you can only save about 10 bits.  It\'s just not worth it.</p>\n\n<p>Having said all that, it also seems very unlikely that any really useful data is truly random.  In case there\'s any more structure to your data, there\'s probably a more optimistic answer.</p>\n'}, {'answer_id': 36943, 'author': 'erickson', 'author_id': 3474, 'author_profile': 'https://Stackoverflow.com/users/3474', 'pm_score': 1, 'selected': False, 'text': '<p>Thanks for the answers. This is what I\'m going to try for dynamically choosing the right method:</p>\n\n<p>I\'ll collect all of the first <em>N</em> hits in a conventional bit array, and choose one of three methods, based on the symmetry of this sample.</p>\n\n<ul>\n<li>If the sample is highly asymmetric,\nI\'ll simply store the indexes to the\nset bits  (or maybe the distance to \nthe next bit) in a list. </li>\n<li>If the sample is highly symmetric,\nI\'ll keep using a conventional bit\narray.</li>\n<li>If the sample is moderately\nsymmetric, I\'ll use a lossless\ncompression method like Huffman\ncoding <a href="https://stackoverflow.com/questions/36106/what-are-some-alternatives-to-a-bit-array#36311">suggested by\nInSciTekJeff</a>.</li>\n</ul>\n\n<p>The boundaries between the asymmetric, moderate, and symmetric regions will depend on the time required by the various algorithms balanced against the space they need, where the relative value of time versus space would be an adjustable parameter. The space needed for Huffman coding is a function of the symmetry, and I\'ll profile that with testing. Also, I\'ll test all three methods to determine the time requirements of my implementation.</p>\n\n<p>It\'s possible (and actually I\'m hoping) that the middle compression method will always be better than the list or the bit array or both. Maybe I can encourage this by choosing a set of Huffman codes adapted for higher or lower symmetry. Then I can simplify the system and just use two methods.</p>\n'}, {'answer_id': 37124, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 1, 'selected': False, 'text': '<p>One more compression thought:</p>\n\n<p>If the bit array is not crazy long, you could try applying the <a href="http://en.wikipedia.org/wiki/Burrows-Wheeler" rel="nofollow noreferrer">Burrows-Wheeler transform</a> before using any repetition encoding, such as Huffman.  A naive implementation would take O(n^2) memory during (de)compression and O(n^2 log n) time to decompress - there are almost certainly shortcuts to be had, as well.  But if there\'s any sequential structure to your data at all, this should really help the Huffman encoding out.</p>\n\n<p>You could also apply that idea to one block at a time to keep the time/memory usage more practical.  Using one block at time could allow you to always keep most of the data structure compressed if you\'re reading/writing sequentially.</p>\n'}, {'answer_id': 89094, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I would strongly consider using range encoding in place of Huffman coding.  In general, range encoding can exploit asymmetry more effectively than Huffman coding, but this is especially so when the alphabet size is so small.  In fact, when the "native alphabet" is simply 0s and 1s, the only way Huffman can get any compression at all is by combining those symbols -- which is exactly what range encoding will do, more effectively.</p>\n'}, {'answer_id': 1008429, 'author': 'bill', 'author_id': 121958, 'author_profile': 'https://Stackoverflow.com/users/121958', 'pm_score': 2, 'selected': False, 'text': '<p>Maybe too late for you, but there is a very fast and memory efficient library for sparse bit arrays (lossless) and other data types based on tries. Look at <a href="http://judy.sourceforge.net/" rel="nofollow noreferrer">Judy arrays</a></p>\n'}]
['https://Stackoverflow.com/questions/36106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3474/']