Arrays can not easily grow but lookup time is very less. i.e. O(1)
Link list can easily grow but lookup time is not efficient. i.e. O(n)
Can we do better than O(n) whle still our data structure grow over time...?
I think hash table offers a solution over.
We can use hash table when speedy Insertion, Deletion and lookup of elements is priority.
So what is hash table anyway?
So Hast table is just an Array coupled with the function which will call Hash Function.
This hash function takes input as key and generate value and decide its place/position in hash table.
e.g. We want to store words using hash table.
We have a hash function which check input key in alphabetical order and then generate value for it and put it into Hash table.
1. Apple as a input to our hash function It generate 0 has a hash value Because it start from alphabet 'a' and store it into hash table at 0th.
2. Same If I gave input Banana then our hash function generate hash value 1.
3. Same for cat.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
Hash Function:
int HashFunction(char* key)
{
// Hash on first letter of string
// Return equivalent Index Value
}
Hash Table:
Index Values
=== ====
0 Apple
1 Banana
2 Cat
3
|
If we want to store "ant" into table as well:
we give "ant" as input to our hash function, what will be the hash value he generate???
If he generate 0th as its also start from alphabet 'a' then in such cases collision will occur.
i.e. Two key hashing to the same index.
Thats why you should have a plan to handle the collision in your hash function.
thee are some methods to resolving collision:
1. Linear probing
2. Separate chaining
http://algs4.cs.princeton.edu/34hash/
http://www.algolist.net/Data_structures/Hash_table/Simple_example