Skip to content

ppmpreetham/hashmap

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 

Repository files navigation

HashMap

Hashmap implemented using linear probing and FNV-1 hash function.

                 PROGRAM
                    β”‚
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚              β”‚              β”‚
     β–Ό              β–Ό              β–Ό
  mapSet()       mapGet()       mapDelete()
     β”‚              β”‚              β”‚
     β”‚              β”‚              β”‚
     β”‚              β–Ό              β–Ό
     β”‚          findEntry()    findEntry()
     β”‚              β”‚              β”‚
     β”‚              β”‚              β”‚
     β”‚              β–Ό              β–Ό
     β”‚         compareKey()    compareKey()
     β”‚
     β”‚
     β–Ό
findEntry()
     β”‚
     β–Ό
compareKey()

Hashing:

FNV-1 Hash Function

hash = 2166136261
for each byte:
    hash ^= byte
    hash *= 16777619

Entry Lookup:

start_index = hash & (capacity - 1)

loop:
    entry = entries[index]

    if entry empty
        return entry

    if keys match
        return entry

    index = (index + 1) & (capacity - 1)

Resizing:

Before
------
[ A ][ B ][ C ][   ][ D ]

After Resize
------------
[   ][ A ][   ][ B ][ C ][   ][ D ][   ]

All Methods:

Insert

mapSet()

  1. compute hash
  2. find slot using probing
  3. insert or overwrite

Average: O(1) Worst: O(n)

mapSet()
 β”œβ”€β”€ growMap()
 β”‚    β”œβ”€β”€ malloc()
 β”‚    β”œβ”€β”€ memset()
 β”‚    β”œβ”€β”€ findEntry()
 β”‚    β”‚    └── compareKey()
 β”‚    └── free()
 β”‚
 └── findEntry()
      └── compareKey()

Lookup

mapGet()

Steps:

  1. compute hash
  2. probe until: key found OR empty bucket

If empty bucket reached: key not present

mapGet()
 └── findEntry()
      └── compareKey()

Delete

mapDelete()

Deletion does not clear the slot, but changes it to: NULL : TOMBSTONE because removing it entirely would break probe chains.

Before
A β†’ B β†’ C

After Delete B
A β†’ NULL : TOMBSTONE β†’ C
mapDelete()
└── findEntry()
└── compareKey()

About

An FNV-1 simple linear probe hashmap implementation in C

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages