Open In App

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 

Hash Function:



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. 

Examples:



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 

Implementation:

// C++ code for implementation of
// Address Calculation Sorting using Hashing
 
#include <bits/stdc++.h>
#include <vector>
 
using namespace std;
 
// Size of the address table (In this case 0-9)
const int SIZE = 10;
 
class Node {
public:
    int data;
    Node* nextNode;
 
    Node(int data = 0) {
        this->data = data;
        this->nextNode = nullptr;
    }
};
 
class LinkedList {
public:
    Node* head;
 
    LinkedList() {
        this->head = nullptr;
    }
 
    // Insert values in such a way that the list remains sorted
    void insert(int data) {
        Node* newNode = new Node(data);
 
        // If there is no node or new Node's value
        // is smaller than the first value in the list,
 
        // Insert new Node in the first place
        if (this->head == nullptr || data < this->head->data) {
            newNode->nextNode = this->head;
            this->head = newNode;
        }
        else {
            Node* current = this->head;
 
            // If the next node is null or its value
            // is greater than the new Node's value,
 
            // Insert new Node in that place
            while (current->nextNode != nullptr && current->nextNode->data < data) {
                current = current->nextNode;
            }
 
            newNode->nextNode = current->nextNode;
            current->nextNode = newNode;
        }
    }
};
 
// This function returns the corresponding address
// of given value in the address table
int hashFunction(int num, int maximum) {
    // Scale the value such that address is between 0 to 9
    int address = static_cast<int>((num * 1.0 / maximum) * (SIZE - 1));
    return address;
}
 
// This function sorts the given list
// using Address Calculation Sorting using Hashing
void addressCalculationSort(vector<int>& arr) {
    // Declare a list of Linked Lists of given SIZE
    vector<LinkedList*> listOfLinkedLists(SIZE, nullptr);
    for (int i = 0; i < SIZE; ++i) {
        listOfLinkedLists[i] = new LinkedList();
    }
 
    // Calculate maximum value in the array
    int maximum = *max_element(arr.begin(), arr.end());
 
    // Find the address of each value
    // in the address table
    // and insert it in that list
    for (int val : arr) {
        int address = hashFunction(val, maximum);
        listOfLinkedLists[address]->insert(val);
    }
 
    // Print the address table
    // after all the values have been inserted
    for (int i = 0; i < SIZE; ++i) {
        Node* current = listOfLinkedLists[i]->head;
        cout << "ADDRESS " << i << ": ";
 
        while (current != nullptr) {
            cout << current->data << " ";
            current = current->nextNode;
        }
 
        cout << endl;
    }
 
    // Assign the sorted values to the input array
    int index = 0;
    for (int i = 0; i < SIZE; ++i) {
        Node* current = listOfLinkedLists[i]->head;
 
        while (current != nullptr) {
            arr[index] = current->data;
            index++;
            current = current->nextNode;
        }
    }
}
 
// Driver code
int main() {
    // giving the input address as follows
    vector<int> arr = {29, 23, 14, 5, 15, 10, 3, 18, 1};
    cout << "Input array: ";
     
    for(auto x : arr)
        cout << x << " ";
     
    cout << endl;
     
     
    // Function call
    addressCalculationSort(arr);
   
    cout << endl;
    cout << "Sorted array: ";
     
    for(auto x : arr)
        cout << x << " ";
         
    cout << endl;
}

                    
// Java code for implementation of
// Address Calculation Sorting using Hashing
import java.util.ArrayList;
 
class Node {
    int data;
    Node nextNode;
 
    Node(int data)
    {
        this.data = data;
        this.nextNode = null;
    }
}
 
class LinkedList {
    Node head;
 
    LinkedList() { this.head = null; }
 
    // Insert values in such a way that the list remains
    // sorted
    void insert(int data)
    {
        Node newNode = new Node(data);
 
        // If there is no node or new Node's value
        // is smaller than the first value in the list,
 
        // Insert new Node in the first place
        if (this.head == null || data < this.head.data) {
            newNode.nextNode = this.head;
            this.head = newNode;
        }
        else {
            Node current = this.head;
 
            // If the next node is null or its value
            // is greater than the new Node's value,
 
            // Insert new Node in that place
            while (current.nextNode != null
                   && current.nextNode.data < data) {
                current = current.nextNode;
            }
            newNode.nextNode = current.nextNode;
            current.nextNode = newNode;
        }
    }
}
 
public class AddressCalculationSorting {
 
    // Size of the address table (In this case 0-9)
    static final int SIZE = 10;
 
    // This function returns the corresponding address
    // of given value in the address table
    static int hashFunction(int num, int maximum)
    {
 
        // Scale the value such that address is between 0 to
        // 9
        int address
            = (int)((num * 1.0 / maximum) * (SIZE - 1));
        return address;
    }
 
    // This function sorts the given list
    // using Address Calculation Sorting using Hashing
    static void
    addressCalculationSort(ArrayList<Integer> arr)
    {
 
        // Declare a list of Linked Lists of given SIZE
        ArrayList<LinkedList> listOfLinkedLists
            = new ArrayList<>(SIZE);
        for (int i = 0; i < SIZE; ++i) {
            listOfLinkedLists.add(new LinkedList());
        }
 
        // Calculate maximum value in the array
        int maximum = arr.stream()
                          .mapToInt(Integer::intValue)
                          .max()
                          .getAsInt();
 
        // Find the address of each value
        // in the address table
        // and insert it in that list
        for (int val : arr) {
            int address = hashFunction(val, maximum);
            listOfLinkedLists.get(address).insert(val);
        }
 
        // Print the address table
        // after all the values have been inserted
        for (int i = 0; i < SIZE; ++i) {
            Node current = listOfLinkedLists.get(i).head;
            System.out.print("ADDRESS " + i + ": ");
            while (current != null) {
                System.out.print(current.data + " ");
                current = current.nextNode;
            }
            System.out.println();
        }
 
        // Assign the sorted values to the input array
        int index = 0;
        for (int i = 0; i < SIZE; ++i) {
            Node current = listOfLinkedLists.get(i).head;
            while (current != null) {
                arr.set(index, current.data);
                index++;
                current = current.nextNode;
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        ArrayList<Integer> arr = new ArrayList<>();
 
        // giving the input address as follows
        arr.add(29);
        arr.add(23);
        arr.add(14);
        arr.add(5);
        arr.add(15);
        arr.add(10);
        arr.add(3);
        arr.add(18);
        arr.add(1);
 
        System.out.print("Input array: ");
        for (int x : arr) {
            System.out.print(x + " ");
        }
        System.out.println();
 
        // Function call
        addressCalculationSort(arr);
 
        System.out.println();
        System.out.print("Sorted array: ");
        for (int x : arr) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}
 
// This code is contributed by Samim Hossain Mondal.

                    
# Python3 code for implementation of
# Address Calculation Sorting using Hashing
 
# Size of the address table (In this case 0-9)
SIZE = 10
 
class Node(object):
 
    def __init__(self, data = None):
        self.data = data
        self.nextNode = None
 
class LinkedList(object):
 
    def __init__(self):
        self.head = None
 
    # Insert values in such a way that the list remains sorted
    def insert(self, data):
        newNode = Node(data)
 
        # If there is no node or new Node's value
        # is smaller than the first value in the list,
 
        # Insert new Node in the first place
        if self.head == None or data < self.head.data:
            newNode.nextNode = self.head
            self.head = newNode
 
        else:
            current = self.head
             
            # If the next node is null or its value
            # is greater than the new Node's value,
 
            # Insert new Node in that place
            while current.nextNode != None \
                    and \
                    current.nextNode.data < data:
                current = current.nextNode
 
            newNode.nextNode = current.nextNode
            current.nextNode = newNode
             
# This function sorts the given list
# using Address Calculation Sorting using Hashing
def addressCalculationSort(arr):
 
    # Declare a list of Linked Lists of given SIZE
    listOfLinkedLists = []
    for i in range(SIZE):
        listOfLinkedLists.append(LinkedList())
 
    # Calculate maximum value in the array
    maximum = max(arr)
 
    # Find the address of each value
    # in the address table
    # and insert it in that list
    for val in arr:
        address = hashFunction(val, maximum)
        listOfLinkedLists[address].insert(val)
     
    # Print the address table
    # after all the values have been inserted
    for i in range(SIZE):
        current = listOfLinkedLists[i].head
        print("ADDRESS " + str(i), end = ": ")
 
        while current != None:
            print(current.data, end = " ")
            current = current.nextNode
 
        print()
     
    # Assign the sorted values to the input array
    index = 0
    for i in range(SIZE):
        current = listOfLinkedLists[i].head
 
        while current != None:
            arr[index] = current.data
            index += 1
            current = current.nextNode
             
 
# This function returns the corresponding address
# of given value in the address table
def hashFunction(num, maximum):
 
    # Scale the value such that address is between 0 to 9
    address = int((num * 1.0 / maximum) * (SIZE-1))
    return address
 
# -------------------------------------------------------
# Driver code
 
# giving the input address as follows
arr = [29, 23, 14, 5, 15, 10, 3, 18, 1]
 
# Printing the Input array
print("\nInput array: " + " ".join([str(x) for x in arr]))
 
# Performing address calculation sort
addressCalculationSort(arr)
 
# printing the result sorted array
print("\nSorted array: " + " ".join([str(x) for x in arr]))

                    
using System;
using System.Collections.Generic;
using System.Linq;
 
class Node
{
    public int Data;
    public Node NextNode;
 
    public Node(int data)
    {
        this.Data = data;
        this.NextNode = null;
    }
}
 
class LinkedList
{
    public Node Head;
 
    public LinkedList()
    {
        this.Head = null;
    }
 
    // Insert values in such a way that the list remains
    // sorted
    public void Insert(int data)
    {
        Node newNode = new Node(data);
 
        // If there is no node or new Node's value
        // is smaller than the first value in the list,
 
        // Insert new Node in the first place
        if (this.Head == null || data < this.Head.Data)
        {
            newNode.NextNode = this.Head;
            this.Head = newNode;
        }
        else
        {
            Node current = this.Head;
 
            // If the next node is null or its value
            // is greater than the new Node's value,
 
            // Insert new Node in that place
            while (current.NextNode != null
                   && current.NextNode.Data < data)
            {
                current = current.NextNode;
            }
            newNode.NextNode = current.NextNode;
            current.NextNode = newNode;
        }
    }
}
 
class AddressCalculationSorting
{
    // Size of the address table (In this case 0-9)
    static readonly int SIZE = 10;
 
    // This function returns the corresponding address
    // of the given value in the address table
    static int HashFunction(int num, int maximum)
    {
        // Scale the value such that the address is between 0 to 9
        int address = (int)((num * 1.0 / maximum) * (SIZE - 1));
        return address;
    }
 
    // This function sorts the given list
    // using Address Calculation Sorting using Hashing
    static void AddressCalculationSort(List<int> arr)
    {
        // Declare a list of Linked Lists of given SIZE
        List<LinkedList> listOfLinkedLists = new List<LinkedList>(SIZE);
        for (int i = 0; i < SIZE; ++i)
        {
            listOfLinkedLists.Add(new LinkedList());
        }
 
        // Calculate the maximum value in the array
        int maximum = arr.Max();
 
        // Find the address of each value
        // in the address table
        // and insert it in that list
        foreach (int val in arr)
        {
            int address = HashFunction(val, maximum);
            listOfLinkedLists[address].Insert(val);
        }
 
        // Print the address table
        // after all the values have been inserted
        for (int i = 0; i < SIZE; ++i)
        {
            Node current = listOfLinkedLists[i].Head;
            Console.Write("ADDRESS " + i + ": ");
            while (current != null)
            {
                Console.Write(current.Data + " ");
                current = current.NextNode;
            }
            Console.WriteLine();
        }
 
        // Assign the sorted values to the input array
        int index = 0;
        for (int i = 0; i < SIZE; ++i)
        {
            Node current = listOfLinkedLists[i].Head;
            while (current != null)
            {
                arr[index] = current.Data;
                index++;
                current = current.NextNode;
            }
        }
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        List<int> arr = new List<int>();
 
        // giving the input address as follows
        arr.Add(29);
        arr.Add(23);
        arr.Add(14);
        arr.Add(5);
        arr.Add(15);
        arr.Add(10);
        arr.Add(3);
        arr.Add(18);
        arr.Add(1);
 
        Console.Write("Input array: ");
        foreach (int x in arr)
        {
            Console.Write(x + " ");
        }
        Console.WriteLine();
 
        // Function call
        AddressCalculationSort(arr);
 
        Console.WriteLine();
        Console.Write("Sorted array: ");
        foreach (int x in arr)
        {
            Console.Write(x + " ");
        }
        Console.WriteLine();
    }
}
// This code is contributed by Samim Hossain Mondal.

                    
// Python3 code for implementation of
// Address Calculation Sorting using Hashing
 
// Size of the address table (In this case 0-9)
const SIZE = 10;
 
class Node {
    constructor(data) {
        this.data = data;
        this.nextNode = null;
    }
}
 
class LinkedList {
    constructor() {
        this.head = null;
    }
 
    // Insert values in such a way that the list remains sorted
    insert(data) {
        const newNode = new Node(data);
 
        // If there is no node or new Node's value
        // is smaller than the first value in the list,
        // Insert new Node in the first place
        if (this.head === null || data < this.head.data) {
            newNode.nextNode = this.head;
            this.head = newNode;
        } else {
            let current = this.head;
 
            // If the next node is null or its value
            // is greater than the new Node's value,
  
            // Insert new Node in that place
            while (current.nextNode !== null && current.nextNode.data < data) {
                current = current.nextNode;
            }
 
            newNode.nextNode = current.nextNode;
            current.nextNode = newNode;
        }
    }
}
 
// This function sorts the given list
// using Address Calculation Sorting using Hashing
function addressCalculationSort(arr) {
    // Declare a list of Linked Lists of given SIZE
    const listOfLinkedLists = [];
 
    for (let i = 0; i < SIZE; i++) {
        listOfLinkedLists.push(new LinkedList());
    }
 
    const maximum = Math.max(...arr);
 
    // Find the address of each value
    // in the address table
    // and insert it in that list
    for (const val of arr) {
        const address = hashFunction(val, maximum);
        listOfLinkedLists[address].insert(val);
    }
 
    // Print the address table
    // after all the values have been inserted
    for (let i = 0; i < SIZE; i++) {
        let current = listOfLinkedLists[i].head;
        process.stdout.write(`ADDRESS ${i}: `);
 
        while (current !== null) {
            process.stdout.write(`${current.data} `);
            current = current.nextNode;
        }
 
        process.stdout.write('\n');
    }
 
    // Assign the sorted values to the input array
    let index = 0;
    for (let i = 0; i < SIZE; i++) {
        let current = listOfLinkedLists[i].head;
 
        while (current !== null) {
            arr[index] = current.data;
            index += 1;
            current = current.nextNode;
        }
    }
}
 
// This function returns the corresponding address
// of given value in the address table
function hashFunction(num, maximum) {
    // Scale the value such that address is between 0 to 9
    const address = Math.floor((num * 1.0 / maximum) * (SIZE - 1));
    return address;
}
 
// Driver code
// giving the input address as follows
const arr = [29, 23, 14, 5, 15, 10, 3, 18, 1];
 
process.stdout.write(`\nInput array: ${arr.join(' ')}\n`);
 
// Performing address calculation sort
addressCalculationSort(arr);
 
// printing the result sorted array
process.stdout.write(`\nSorted array: ${arr.join(' ')}\n`);
 
//contributed by Aditya Sharma

                    

Output
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


Time Complexity: 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.


Article Tags :