Search Algorithms Flashcards
Time complexity of linear search
O(n)
Time complexity of binary search
O(log n)
Time complexity of hash table search
Without collision resolution: O(1)
With collision resolution: O(n)
For a hash table, a hash function should:
- Take an input key of any length
- Return a location of fixed length
- Location should be unique to the key
Returns an output hash index of fixed size
For a hash table, a key should be:
Immutable (so that its hashed location is always the same)
Features of an ideal hash function
- Use all input data
- Small difference in input results in large difference in hash value
- Output should be uniformly distributed across all possible hash values
The key steps for Binary Search are:
- Handle the base case (empty/single-element array)
- Initialise
start = 0
andend = array.length - 1
- Determine middle index
mid
- Check item at
mid
:- if match, return
mid
- if search key less than mid item, update
end
tomid - 1
- if search key greater than mid item, update
start
tomid + 1
- if match, return
- If
start > end
(no match found), return none or display/raise error, else repeat from step 3
collision resolution
open addressing (generation of new location):
1. hash key to location
2. if key matches store key and value pair at location
3. else, rehash key to new location and repeat step 2
4. if no more location available return error
close addressing (each location in the table is a linked list):
1. hash key to location
2. check if linked list at location have the key (yes, end/ update)
3. else, add key-pair value to end of linked list