11-Searching and Hashing Final
11-Searching and Hashing Final
vs
Binary Search
Kumkum Saxena
Linear Search
◼ Your code should look something like this:
int i;
for (i=0; i<len; i++) {
if (array[i] == value)
return 1;
}
return 0;
}
return 0;
}
Kumkum Saxena Searching and Hashing page 10
Binary Search
◼ Binary Search code:
Kumkum Saxena
Terminology
◼ Table
◼ An abstract data type that stores & retrieves
records according to their search key values
◼ Record
◼ Each individual row in the table
◼ Example:
◼ A database of student records
◼ So each record will have a pid, first name, last name,
SSN, address, phone, email, etc.
...
◼ Hashing
◼ A way to access a table (array) in relatively
constant (quick) time
◼ Uses a hash function & collision resolution scheme
Kumkum Saxena Searching and Hashing page 32
Hash Example
◼ UCF System for storing student records
◼ Could store everyone’s records with name,
address, and telephone number using SSN as the
search key
◼ Could use entire SSN, but wastes too much space
▪ Again, SSN’s have 9 digits…that’s 1 BILLION different #’s to
account for
▪ But UCF has only 50,000 students...so in an array of size 1
BILLION, only 50,000 spots will be used
▪ EPIC WASTE!
▪ On a side note, there will be no “collisions”
▪ Each record will have its own, personal spot in the array based
on its key (phone number)
no collision
collision in small cluster
no collision
[R. Sedgewick]
55
Kumkum Saxena Searching and Hashing page 55
Open Addressing
◼ Quadratic probing
◼ Instead of checking the next location
sequentially, check the next location based on
a sequence of squares
◼ In other words, if table[i] is occupied, check
table[i+12], table[i+22], table[i+32], …
◼ Still have clustering (called “secondary clustering”),
but this method is not as problematic as linear
probing
60
Kumkum Saxena Searching and Hashing page 60
Quadratic Probing: Properties
◼ For any < ½, quadratic probing will find an empty
slot; for bigger , quadratic probing may find a slot
61
Kumkum Saxena Searching and Hashing page 61
Open Addressing
◼ Double hashing example
◼ Table size = 31
◼ Hash function #1 = key mod 31
◼ Hash function #2 = 23 – (key mod 23)
◼ h1(1234) = 25 table[25] = 1234
◼ h1(4055) = 25, h2(4055) = 16 (+25),table[10] = 4055
◼ h1(3962) = 25, h2(3962) = 17 (+25), table[11] = 3962
◼ h1(5853) = 25, h2(5853) = 12 (+25), table[6] = 5853
◼ h1(1766) = 30 table[30] = 1766
◼ h1(1270) = 30, h2(1270) = 18 (+30), table[17] = 1270
◼ All other table entries are empty