Hashing is a method of sorting and indexing data. The idea behind hashing is to allow large amount of data to be indexed using keys commonly created by formulas.
Why do we need hashing
It is time efficient in case of search operation.
Data Structure | Time Complexity of Search |
Array | O(logN) |
LinkedList | O(N) |
Tree | O(logN) |
Hashing | O(1)/O(N) |
Hashing terminology
- Hash function:- It is a function that can be used to map of arbitrary size to data of fixed size.
- Key:- Input data by a user
- Hash value:- A value that is returned by hash function.
- Hash table:- It is a data structure which implements an associative array abstract data type, a structure that can map keys to values.
- Collision:- A collision occurs when two different keys to a hash function produces the same output.
- if hash function is having less collision in case hash function perform very well
Hash Functions
/**
* @param number number which you want to insert
* @param cellNumber total number of cells you want
* @return it will return reminder
*/
//it is mod function
public static int mod(int number, int cellNumber) {
return (number % cellNumber);
}
/**
* @param word which word you want to insert
* @param cellNumber total cells you want
* @return it will return reminder
*/
// it is modASCII
public static int modASCII(String word, int cellNumber) {
int total = 0;
for (int i = 0; i < word.length(); i++) {
total += word.charAt(i);
System.out.println("char at " + word.charAt(i));
System.out.println(total + " total");
}
return total % cellNumber;
}
Properties of hash function
It distributes hash value across hash tables.
What will happen if hash table is full.
Practical use of hashing
Store hashvalue insted of actual password.
File system:- file path is mapped to physical location on disk.