Skip to content

Instantly share code, notes, and snippets.

@veeara282
Created October 1, 2017 00:58
Show Gist options
  • Save veeara282/7b08e9a10e657affe85121fcfdc30b08 to your computer and use it in GitHub Desktop.
Save veeara282/7b08e9a10e657affe85121fcfdc30b08 to your computer and use it in GitHub Desktop.
Sort a bit vector in O(n) time
import java.util.BitSet;
public class BitSort {
public BitSet sort(BitSet bits) {
// Count the number of ones: O(n)
int numOnes = bits.cardinality();
// Overwrite the array with the ones first followed by the zeros
bits.set(0, numOnes);
bits.clear(numOnes, bits.size());
return bits;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment