Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a HashMap in C [closed]

How to go about creating a Hashmap in C from scratch as is present in C++ STL?

What parameters would be taken into consideration and how would you test the hashmap? As in, what would the benchmark test cases be which you would run before you could say that your hashmap is complete?

like image 361
Thunderboltz Avatar asked May 08 '09 05:05

Thunderboltz


People also ask

How is a HashMap implemented in C?

There are two common styles of hashmap implementation: Separate chaining: one with an array of buckets (linked lists) Open addressing: a single array allocated with extra space so index collisions may be resolved by placing the entry in an adjacent slot.

Is HashMap present in C?

hashmap. c source code is available under the MIT License.

How is a HashMap implemented?

Hashmap uses the array of Nodes(named as table), where Node has fields like the key, value (and much more). Here the Node is represented by class HashMapEntry. Basically, HashMap has an array where the key-value data is stored. It calculates the index in the array where the Node can be placed and it is placed there.

Is HashMap always constant time?

Whatever may be the size of the data, HashMap almost gives constant time performance for most frequent operations – insertion and retrieval. That's why HashMap is the first choice for the big sized data having requirement of faster retrieval and faster insertion operations.


1 Answers

Well if you know the basics behind them, it shouldn't be too hard.

Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.

When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.

Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).

Check out this fast hash table implementation:

https://attractivechaos.wordpress.com/2009/09/29/khash-h/

like image 115
Unknown Avatar answered Oct 11 '22 12:10

Unknown