There is an A set of elements indexed [0, n]. At any time at most m elements from an A set can be active (in use), with an obvious condition that 0 <= m <= n. I would like to index those active elements inside a local array. An element can be deactivated dynamically while the program is executing and I would prefer that its index could be reused, when new elements are activated.
I would like to map an element index to it’s local index in the most efficient way as I’m using the local index for fast lookup of active element data.
Possible solutions of trivial hash function (element index == local index) and brute forcing through an associative list do not scale well with large n.
Dynamic expansion/shrinking of data structure is an obvious plus.
Thank you
There ain’t no such thing as the fastest code (tanstatfc) – Michael Abrash
There are many solutions to your problem.
First step is to choose a datastructure and a hash function.
Datastructure can be:
1 Plain array
This is the simplest solution. And if your allocations are blobby (that means they are clustered together in space) this might even be a good solution.
Here’s how it works:
You can fit 2GB / 4bytes per entry = 500 million entries in this structure.
This works best for data that grouped in clusters that are close together.
If the indexes are random, this will be inefficient.
Here’s Delphi pseudo code:
Example code for straight list using Virtual memory
2 Array with linked list
This works best for data that has a very random index, with little change of colliding.
The success depends critically upon your hash function, it needs to select a different array entry as much as possible, too many
collisionsand you will just be walking the same linked list all the time.Example code for array of linked lists
3 binary tree using the bit in the index to traverse the tree
Example code using a binary tree
Recommend reading:
Knuth: TAOCP I: fundamental algorithms, chapter 2 ISBN 0-201-03809-9
Cormen, Leiserson & Rivest: Introduction to Algorithms, chapter III Data structures ISBN 0-07-013143-0