Address Calculation Sort using Hashing
In this sorting algorithm, Hash Function f is used with the property of Order Preserving Function which states that if .
f(x) = floor( (x/maximum) * SIZE ) where maximum => maximum value in the array, SIZE => size of the address table (10 in our case), floor => floor function
This algorithm uses an address table to store the values which is simply a list (or array) of Linked lists. The Hash function is applied to each value in the array to find its corresponding address in the address table. Then the values are inserted at their corresponding addresses in a sorted manner by comparing them to the values which are already present at that address.
Input : arr = [29, 23, 14, 5, 15, 10, 3, 18, 1] Output: After inserting all the values in the address table, the address table looks like this: ADDRESS 0: 1 --> 3 ADDRESS 1: 5 ADDRESS 2: ADDRESS 3: 10 ADDRESS 4: 14 --> 15 ADDRESS 5: 18 ADDRESS 6: ADDRESS 7: 23 ADDRESS 8: ADDRESS 9: 29
The below figure shows the representation of the address table for the example discussed above:
After insertion, the values at each address in the address table are sorted. Hence we iterate through each address one by one and insert the values at that address in the input array.
Below is the implementation of the above approach
Input array: 29 23 14 5 15 10 3 18 1 ADDRESS 0: 1 3 ADDRESS 1: 5 ADDRESS 2: ADDRESS 3: 10 ADDRESS 4: 14 15 ADDRESS 5: 18 ADDRESS 6: ADDRESS 7: 23 ADDRESS 8: ADDRESS 9: 29 Sorted array: 1 3 5 10 14 15 18 23 29
The time complexity of this algorithm is in the best case. This happens when the values in the array are uniformly distributed within a specific range.
Whereas the worst case time complexity is . This happens when most of the values occupy 1 or 2 addresses because then significant work is required to insert each value at its proper place.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.