Computer Science Notes

Notes From CS Undergrad Courses FSU

This project is maintained by awa03

Hash Tables support insert, remove and search in O(1) time.

[!IMPORTANT] Idea Behind Hash Table: O(1) is the worst case for insert, remove, search

Issues that need to be solved

Hashing

![[Firefox_Screenshot_2023-11-16T19-54-40.989Z.png]]

Applications of Hash Tables

Hashing Functions

Simple Function

Another Example

Hashing a Sequence of Keys

Use the Entire Key

unsigned int Hash(const string& Key){
	unsigned int hash = 0;
	for(string::size_type k =0; j !- K.size();++j) 
	{
		hash = hash ^ Key[j]; // Xor
	}
	return hash;
}
// Problem: Hash("ab") == Hash("ba")

Use the Ordering Information

unsigned int Hash(const string &Key){
	unsigned int hash = 0;
	for(size_type j =0; j != Key.size(); ++j)
	{
		hash = hash ^ Key[j]; // Xor The Key Value
		// uses on a bit level
		// 101 ^ 001 = 100
		hash = hash * (j % 32);
	}
	return hash;
}

Better Hash Function

unsigned int Hash(const string& S){
	size_type i;
	long unsigned int bigval = S[0];
	for(i = 1; i < S.size(); ++i){
		// low16 * magicNumber
		bigval = ((bigval & 65535) * 18000)
		+ (bigcal >> 16) // high16
		+ S[i]; 
	}
	bigval = ((bigval & 65535) * 18000) + (bigval >> 16);
	// bigval = low16 * magicNumber + high16

	// return low16
	return bigval & 65535;

}

Even if the function just returned 0 it would still be a legit hash function. Replacing the hash function in any hash table with this would still work but the O(1) complexity may not be maintained.