Open In App

Sorting using trivial hash function

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We have read about various sorting algorithms such as heap sort, bubble sort, merge sort and others. 
Here we will see how can we sort N elements using a hash array. But this algorithm has a limitation. We can sort only those N elements, where the value of elements is not large (typically not above 10^6).

Examples:  

Input :  9 4 3 5 8 
Output : 3 4 5 8 9

Explanation of sorting using hash:

  • Step 1: Create a hash array of size(max_element), since that is the maximum we will need 
  • Step 2: Traverse through all the elements and keep a count of number of occurrence of a particular element. 
  • Step 3: After keeping a count of occurrence of all elements in the hash table, simply iterate from 0 to max_element in the hash array 
  • Step 4: While iterating in the hash array, if we find the value stored at any hash position is more than 0, which indicated that the element is present at least once in the original list of elements. 
  • Step 5: Hash[i] has the count of the number of times an element is present in the list, so when its >0, we print those number of times the element. 
     
  • If you want to store the elements, use another array to store them in a sorted way. 
  • If we want to sort it in descending order, we simply traverse from max to 0 and repeat the same procedure.

Below is the implementation of the above approach: 

C++




// C++ program to sort an array using hash
// function
#include <bits/stdc++.h>
using namespace std;
 
void sortUsingHash(int a[], int n)
{
    // find the maximum element
    int max = *std::max_element(a, a + n);
 
    // create a hash function upto the max size
    int hash[max + 1] = { 0 };
 
    // traverse through all the elements and
    // keep a count
    for (int i = 0; i < n; i++)
        hash[a[i]] += 1;
 
    // Traverse upto all elements and check if
    // it is present or not. If it is present,
    // then print the element the number of times
    // it's present. Once we have printed n times,
    // that means we have printed n elements
    // so break out of the loop
    for (int i = 0; i <= max; i++) {
 
        // if present
        if (hash[i]) {
 
            // print the element that number of
            // times it's present
            for (int j = 0; j < hash[i]; j++) {
                cout << i << " ";
            }
        }
    }
}
 
// driver program
int main()
{
    int a[] = { 9, 4, 3,  2,  5,  2,  1,  0, 4,
                3, 5, 10, 15, 12, 18, 20, 19 };
    int n = sizeof(a) / sizeof(a[0]);
 
    sortUsingHash(a, n);
    return 0;
}


Java




// Java program to sort an array using hash
// function
import java.util.*;
 
class GFG {
 
    static void sortUsingHash(int a[], int n)
    {
        // find the maximum element
        int max = Arrays.stream(a).max().getAsInt();
 
        // create a hash function upto the max size
        int hash[] = new int[max + 1];
 
        // traverse through all the elements and
        // keep a count
        for (int i = 0; i < n; i++)
            hash[a[i]] += 1;
 
        // Traverse upto all elements and check if
        // it is present or not. If it is present,
        // then print the element the number of times
        // it's present. Once we have printed n times,
        // that means we have printed n elements
        // so break out of the loop
        for (int i = 0; i <= max; i++) {
 
            // if present
            if (hash[i] != 0) {
 
                // print the element that number of
                // times it's present
                for (int j = 0; j < hash[i]; j++) {
                    System.out.print(i + " ");
                }
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a[] = { 9, 4, 325210, 4,
                    3, 5, 10, 15, 12, 18, 20, 19 };
        int n = a.length;
 
        sortUsingHash(a, n);
    }
}
 
// This code contributed by Rajput-Ji


Python3




# Python3 program to sort an array
# using hash function
 
 
def sortUsingHash(a, n):
 
    # find the maximum element
    Max = max(a)
 
    # create a hash function upto
    # the max size
    Hash = [0] * (Max + 1)
 
    # traverse through all the elements
    # and keep a count
    for i in range(0, n):
        Hash[a[i]] += 1
 
    # Traverse upto all elements and check
    # if it is present or not. If it is
    # present, then print the element the
    # number of times it's present. Once we
    # have printed n times, that means we
    # have printed n elements so break out
    # of the loop
    for i in range(0, Max + 1):
 
        # if present
        if Hash[i] != 0:
 
            # print the element that number
            # of times it's present
            for j in range(0, Hash[i]):
                print(i, end=" ")
 
 
# Driver Code
if __name__ == "__main__":
 
    a = [9, 4, 3, 2, 5, 2, 1, 0, 4,
         3, 5, 10, 15, 12, 18, 20, 19]
    n = len(a)
 
    sortUsingHash(a, n)
 
# This code is contributed by Rituraj Jain


C#




// C# program to sort an array using hash
// function
using System;
using System.Linq;
 
class GFG {
 
    static void sortUsingHash(int[] a, int n)
    {
        // find the maximum element
        int max = a.Max();
 
        // create a hash function upto the max size
        int[] hash = new int[max + 1];
 
        // traverse through all the elements and
        // keep a count
        for (int i = 0; i < n; i++)
            hash[a[i]] += 1;
 
        // Traverse upto all elements and check if
        // it is present or not. If it is present,
        // then print the element the number of times
        // it's present. Once we have printed n times,
        // that means we have printed n elements
        // so break out of the loop
        for (int i = 0; i <= max; i++) {
 
            // if present
            if (hash[i] != 0) {
 
                // print the element that number of
                // times it's present
                for (int j = 0; j < hash[i]; j++) {
                    Console.Write(i + " ");
                }
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] a = { 9, 4, 3,  2,  5,  2,  1,  0, 4,
                    3, 5, 10, 15, 12, 18, 20, 19 };
        int n = a.Length;
 
        sortUsingHash(a, n);
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
// javascript program to sort an array using hash
// function
 
    function sortUsingHash(a, n) {
        // find the maximum element
        var max = Math.max.apply(Math, a);
 
        // create a hash function upto the max size
        var hash = Array(max + 1).fill(0);
 
        // traverse through all the elements and
        // keep a count
        for (i = 0; i < n; i++)
            hash[a[i]] += 1;
 
        // Traverse upto all elements and check if
        // it is present or not. If it is present,
        // then print the element the number of times
        // it's present. Once we have printed n times,
        // that means we have printed n elements
        // so break out of the loop
        for (i = 0; i <= max; i++) {
 
            // if present
            if (hash[i] != 0) {
 
                // print the element that number of
                // times it's present
                for (j = 0; j < hash[i]; j++) {
                    document.write(i + " ");
                }
            }
        }
    }
 
    // Driver code
     
        var a = [ 9, 4, 3, 2, 5, 2, 1, 0, 4, 3, 5, 10, 15, 12, 18, 20, 19 ];
        var n = a.length;
 
        sortUsingHash(a, n);
 
// This code contributed by Rajput-Ji
</script>


Output

0 1 2 2 3 3 4 4 5 5 9 10 12 15 18 19 20 

Time Complexity: O(max*n), where max is maximum element and n is the length of given array
Auxiliary Space: O(max)
 

How to handle negative numbers? 

In case the array has negative numbers and positive numbers, we keep two hash arrays to keep a track of positive and negative elements.

Explanation of sorting using hashing if the array has negative and positive numbers: 

  • Step 1: Create two hash arrays, one for positive and the other for negative 
  • Step 2: the positive hash array will have a size of max and the negative array will have a size of min 
  • Step 3: traverse from min to 0 in the negative hash array, and print the elements in the same way we did for positives. 
  • Step 4: Traverse from 0 to max for positive elements and print them in the same manner as explained above. 

Below is the implementation of the above approach: 

C++




// C++ program to sort an array using hash
// function with negative values allowed.
#include <bits/stdc++.h>
using namespace std;
 
void sortUsingHash(int a[], int n)
{
    // find the maximum element
    int max = *std::max_element(a, a + n);
    int min = abs(*std::min_element(a, a + n));
 
    // create a hash function upto the max size
    int hashpos[max + 1] = { 0 };
    int hashneg[min + 1] = { 0 };
 
    // traverse through all the elements and
    // keep a count
    for (int i = 0; i < n; i++) {
        if (a[i] >= 0)
            hashpos[a[i]] += 1;
        else
            hashneg[abs(a[i])] += 1;
    }
 
    // Traverse up to all negative elements and
    // check if it is present or not. If it is
    // present, then print the element the number
    // of times it's present. Once we have printed
    // n times, that means we have printed n elements
    // so break out of the loop
    for (int i = min; i > 0; i--) {
        if (hashneg[i]) {
 
            // print the element that number of times
            // it's present. Print the negative element
            for (int j = 0; j < hashneg[i]; j++) {
                cout << (-1) * i << " ";
            }
        }
    }
 
    // Traverse upto all elements and check if it is
    // present or not. If it is present, then print
    // the element the number of times it's present
    // once we have printed n times, that means we
    // have printed n elements, so break out of the
    // loop
    for (int i = 0; i <= max; i++) {
 
        // if present
        if (hashpos[i]) {
 
            // print the element that number of times
            // it's present
            for (int j = 0; j < hashpos[i]; j++) {
                cout << i << " ";
            }
        }
    }
}
 
// driver program to test the above function
int main()
{
    int a[] = { -1, -2, -3, -4, -5, -6, 8,
                7,  5,  4,  3,  2,  1,  0 };
    int n = sizeof(a) / sizeof(a[0]);
    sortUsingHash(a, n);
    return 0;
}


Java




// Java program to sort an array using hash
// function with negative values allowed.
import java.util.Arrays;
class GFG {
 
    static int absolute(int x)
    {
        if (x < 0)
            return (-1 * x);
        return x;
    }
 
    static void sortUsingHash(int a[], int n)
    {
        // find the maximum element
        int max = Arrays.stream(a).max().getAsInt();
        int min
            = absolute(Arrays.stream(a).min().getAsInt());
 
        // create a hash function upto the max size
        int hashpos[] = new int[max + 1];
        int hashneg[] = new int[min + 1];
 
        // traverse through all the elements and
        // keep a count
        for (int i = 0; i < n; i++) {
            if (a[i] >= 0)
                hashpos[a[i]] += 1;
            else
                hashneg[absolute(a[i])] += 1;
        }
 
        // Traverse up to all negative elements and
        // check if it is present or not. If it is
        // present, then print the element the number
        // of times it's present. Once we have printed
        // n times, that means we have printed n elements
        // so break out of the loop
        for (int i = min; i > 0; i--) {
            if (hashneg[i] > 0) {
 
                // print the element that number of times
                // it's present. Print the negative element
                for (int j = 0; j < hashneg[i]; j++) {
                    System.out.print((-1) * i + " ");
                }
            }
        }
 
        // Traverse upto all elements and check if it is
        // present or not. If it is present, then print
        // the element the number of times it's present
        // once we have printed n times, that means we
        // have printed n elements, so break out of the
        // loop
        for (int i = 0; i <= max; i++) {
 
            // if present
            if (hashpos[i] > 0) {
 
                // print the element that number of times
                // it's present
                for (int j = 0; j < hashpos[i]; j++) {
                    System.out.print(i + " ");
                }
            }
        }
    }
 
    // Driver program to test the above function
    public static void main(String[] args)
    {
        int a[] = { -1, -2, -3, -4, -5, -6, 8,
                    7543210 };
        int n = a.length;
        sortUsingHash(a, n);
    }
}
 
// This code has been contributed by 29AjayKumar


Python3




# Python3 program to sort an array using hash
# function with negative values allowed.
 
 
def sortUsingHash(a, n):
 
    # find the maximum element
    Max = max(a)
    Min = abs(min(a))
 
    # create a hash function upto the max size
    hashpos = [0] * (Max + 1)
    hashneg = [0] * (Min + 1)
 
    # traverse through all the elements and
    # keep a count
    for i in range(0, n):
        if a[i] >= 0:
            hashpos[a[i]] += 1
        else:
            hashneg[abs(a[i])] += 1
 
    # Traverse up to all negative elements
    # and check if it is present or not.
    # If it is present, then print the
    # element the number of times it's present.
    # Once we have printed n times, that means
    # we have printed n elements so break out
    # of the loop
    for i in range(Min, 0, -1):
        if hashneg[i] != 0:
 
            # print the element that number of times
            # it's present. Print the negative element
            for j in range(0, hashneg[i]):
                print((-1) * i, end=" ")
 
    # Traverse upto all elements and check if
    # it is present or not. If it is present,
    # then print the element the number of
    # times it's present once we have printed
    # n times, that means we have printed n
    # elements, so break out of the loop
    for i in range(0, Max + 1):
 
        # if present
        if hashpos[i] != 0:
 
            # print the element that number
            # of times it's present
            for j in range(0, hashpos[i]):
                print(i, end=" ")
 
 
# Driver Code
if __name__ == "__main__":
 
    a = [-1, -2, -3, -4, -5, -6,
         8, 7, 5, 4, 3, 2, 1, 0]
 
    n = len(a)
    sortUsingHash(a, n)
 
# This code is contributed by Rituraj Jain


C#




// C# program to sort an array using hash
// function with negative values allowed.
using System;
using System.Linq;
 
class GFG {
 
    static int absolute(int x)
    {
        if (x < 0)
            return (-1 * x);
        return x;
    }
 
    static void sortUsingHash(int[] a, int n)
    {
        // find the maximum element
        int max = a.Max();
        int min = absolute(a.Min());
 
        // create a hash function upto the max size
        int[] hashpos = new int[max + 1];
        int[] hashneg = new int[min + 1];
 
        // traverse through all the elements and
        // keep a count
        for (int i = 0; i < n; i++) {
            if (a[i] >= 0)
                hashpos[a[i]] += 1;
            else
                hashneg[absolute(a[i])] += 1;
        }
 
        // Traverse up to all negative elements and
        // check if it is present or not. If it is
        // present, then print the element the number
        // of times it's present. Once we have printed
        // n times, that means we have printed n elements
        // so break out of the loop
        for (int i = min; i > 0; i--) {
            if (hashneg[i] > 0) {
 
                // print the element that number of times
                // it's present. Print the negative element
                for (int j = 0; j < hashneg[i]; j++) {
                    Console.Write((-1) * i + " ");
                }
            }
        }
 
        // Traverse upto all elements and check if it is
        // present or not. If it is present, then print
        // the element the number of times it's present
        // once we have printed n times, that means we
        // have printed n elements, so break out of the
        // loop
        for (int i = 0; i <= max; i++) {
 
            // if present
            if (hashpos[i] > 0) {
 
                // print the element that number of times
                // it's present
                for (int j = 0; j < hashpos[i]; j++) {
                    Console.Write(i + " ");
                }
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] a = { -1, -2, -3, -4, -5, -6, 8,
                    7,  5,  4,  3,  2,  1,  0 };
        int n = a.Length;
        sortUsingHash(a, n);
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
// javascript program to sort an array using hash
// function with negative values allowed.
 
 
function absolute(int x){
    if(x<0)    return (-1*x);
    return x;
}
 
    function sortUsingHash(a, n) {
        // find the maximum element
        var max = Math.max.apply(Math, a);
        var min = absolute(Math.min.apply(Math, a));
 
        // create a hash function upto the max size
        var hashpos =  Array(max).fill(0);
        var hashneg = Array(min + 1).fill(0);
 
        // traverse through all the elements and
        // keep a count
        for (i = 0; i < n; i++) {
            if (a[i] >= 0)
                hashpos[a[i]] += 1;
            else
                hashneg[absolute(a[i])] += 1;
        }
 
        // Traverse up to all negative elements and
        // check if it is present or not. If it is
        // present, then print the element the number
        // of times it's present. Once we have printed
        // n times, that means we have printed n elements
        // so break out of the loop
        for (i = min; i > 0; i--) {
            if (hashneg[i] > 0) {
 
                // print the element that number of times
                // it's present. Print the negative element
                for (j = 0; j < hashneg[i]; j++) {
                    document.write((-1) * i + " ");
                }
            }
        }
 
        // Traverse upto all elements and check if it is
        // present or not. If it is present, then print
        // the element the number of times it's present
        // once we have printed n times, that means we
        // have printed n elements, so break out of the
        // loop
        for (i = 0; i <= max; i++) {
 
            // if present
            if (hashpos[i] > 0) {
 
                // print the element that number of times
                // it's present
                for (j = 0; j < hashpos[i]; j++) {
                    document.write(i + " ");
                }
            }
        }
    }
 
    // Driver program to test the above function
     
        var a = [ -1, -2, -3, -4, -5, -6, 8, 7, 5, 4, 3, 2, 1, 0 ];
        var n = a.length;
        sortUsingHash(a, n);
 
// This code contributed by Rajput-Ji
</script>


Output

-6 -5 -4 -3 -2 -1 0 1 2 3 4 5 7 8 

Complexity: 
Time complexity- The time complexity of this program is O(n + max), where n is the size of the input array and max is the maximum element in the array. This is because the program first finds the maximum element in the array using std::max_element, which takes O(n) time. It then creates two hash arrays of size max+1 and min+1, where min is the absolute value of the minimum element in the array. This takes O(max+min) time, but since min is always less than or equal to max, we can simplify this to O(max). The program then traverses through the input array once to fill in the hash arrays, which takes O(n) time. Finally, the program traverses through the two hash arrays, printing out the elements in sorted order. This takes O(max) time, since max is the size of the hash arrays. Therefore, the total time complexity of the program is O(n + max).

Space complexity –The space complexity of this program is O(max), since the program creates two hash arrays of size max+1 and min+1, where min is the absolute value of the minimum element in the array. However, since min is always less than or equal to max, we can simplify this to O(max). Therefore, the space complexity of the program is O(max).

Limitations: 

  1. Can only sort array elements of limited range (typically from -10^6 to +10^6) 
  2. Auxiliary space in worst cases is O(max_element) + O(min_element)


Previous Article
Next Article

Similar Reads

Index Mapping (or Trivial Hashing) with negatives allowed
Index Mapping (also known as Trivial Hashing) is a simple form of hashing where the data is directly mapped to an index in a hash table. The hash function used in this method is typically the identity function, which maps the input data to itself. In this case, the key of the data is used as the index in the hash table, and the value is stored at t
7 min read
What are Hash Functions and How to choose a good Hash Function?
Prerequisite: Hashing | Set 1 (Introduction) What is a Hash Function? A function that converts a given big phone number to a small practical integer value. The mapped integer value is used as an index in the hash table. In simple terms, a hash function maps a big number or string to a small integer that can be used as the index in the hash table. W
5 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Sorting objects using In-Place sorting algorithm
Given an array of red, blue and yellow objects, the task is to use an in-place sorting algorithm to sort the array in such a way that all the blue objects appear before all the red objects and all the red objects appear before all the yellow objects.Examples: Input: arr[] = {"blue", "red", "yellow", "blue", "yellow"} Output: blue blue red yellow ye
7 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
What is Sorting in DSA | Sorting meaning
Sorting is defined as the process of arranging a collection of data elements in a specific order, usually in ascending or descending order based on a specific attribute of the data elements. Characteristics of Sorting:Time Complexity: Time complexity, a measure of how long it takes to run an algorithm, is used to categorize sorting algorithms. The
3 min read
Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
Ever wondered how sort() function we use in C++/Java or sorted() in Python work internally? Here is a list of all the inbuilt sorting algorithms of different programming languages and the algorithm they use internally. C’s qsort() – QuicksortBest Case Time Complexity- O(NlogN)Average Case Time Complexity- O(NlogN)Worse Case Time Complexity- O(N2)Au
2 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read
Count Distinct Strings present in an array using Polynomial rolling hash function
Given an array of strings arr[], the task is to find the count of distinct strings present in the array using polynomial rolling hash function. Examples: Input: arr[] = { "abcde", "abcce", "abcdf", "abcde", "abcdf" } Output: 3 Explanation: Distinct strings in the array are { "abcde", "abcce", "abcdf" }. Therefore, the required output is 3. Input: a
7 min read
Practice Tags :
three90RightbarBannerImg