I am reading on some problems that are about optimization approaches.
In the problem how to sort numbers in a specific range the solution is to use a bitmap. And if a number can appear e.g. up to 10 times use to use half bytes to map the numbers and as counters to represent the number of occurences.
The concept I understand well. My problem is how to implement this in Java in a straightforward manner.
I am stuck on bit operations.
For example for the first part to increment the counter by 1, what I could think about was:
Locate the byte
E.g. bitValue[i]
Then do byte tmp = bitValue[i] & 0x0F
to get the lower bits (if the counter is the low counter).
Then do tmp = tmp + 1
to increment by 1.
Then do bitValue[i] >> 2
to clear low end bits and then bitValue[i] <<2
to restore. Now we have the same high bits as the original and the low bits clear.
Then do bitValue[i] |= tmp
to set low bits.
Now bitValue
has the low bit counter incremented by 1. Right?
For the upper bit it would be the same process but for the upper bits.
Then when I have to check what is the number of the counter.
I thought to use bitmasks:
0x0
0x1
0x2
etc and use OR
to check what is the current counter number.
All these seem to be too complicated. Am I on the right track? How are these operations addressed best in java coding?
Any input, guidance on this is highly welcome.