Memory efficient Sorting/Storing of Integer Arrays:Bitmapping
How about creating a number array in C with each element using just one bit of memory?There is no doubt that there are no datatypes in C whose size is 1 bit.Then how?What more,the list gets automatically sorted!
Click here to see code:Storing array using Bitmapping with BitArray(simple and short,requires basic knowledge of bit operations)
Click here to see code :Storing array using Bitmapping with BitFields(long and boring,just a test code,using simple logic)
Demerits of bitmapping:
1.No repetitions allowed.All redundant entries will be ignored,and just one will remain.
2.It may result in wastage of memory when the upper limit of list is large while list is small.(For eg,a list with upper_limit=5000 and containing 10 entries will be alloted 626 bytes). So it is recommended only when the number of entries are comparable to the upper_limit.
Merits of bitmapping
1.Uses only approximately largest_number/8 bytes.
2.The list is automatically sorted,without any sorting procedures.
The storage technique is based on a concept named bitmapping.Instead of storing the number in the memory,you make use of the index of the array.And in the memory,you store 1 if the index is present in the list else 0.
A short note on Bit Fields
Again,How can you store "1" in 1 bit?Well the answer is Bitfields .It is a very helpful when there is no need to allot 4 bytes for an integer,and the task may be done with a few bits.For eg a boolean element needs just one bit to store 0 or 1.Likewise,to store numbers from 0 to 3,you just need two bits.In such occasions we may use bit fields.
struct bits
{
//This is just an example.Please read the section below
unsigned char gender:1;
}
Memory Padding
Another fact to be noted is about memory padding.Even if a structure of size one bit is created,its size would be equal to the size of datatype.For example the above structure would have a size of 1 byte.(refer Data structure alignment).So for efficient use of the bitfelds,use all the bits,For eg
struct bits
{
unsigned char num1:1;
unsigned char num2:1;
unsigned char num3:1;
unsigned char num4:1;
unsigned char num5:1;
unsigned char num6:1;
unsigned char num7:1;
unsigned char num8:1;
}
The above structure uses only one bit!So you have 8 variables in 1 byte,ie one bit per variable.
To assign a value to a bit sized variable,you will have to use const or #define and create constants.Then they may be treated just like integers.
#define TRUE 1
const FALSE 0;
main()
{
struct bits eg;
eg.num1=TRUE;
}