Sorting using trivial hash function

Sorting using trivial hash function.

Examples:

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

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).

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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, 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 Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 */

chevron_right



Output:

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

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to sort an array using hash
// function with negative values allowed.
import java.util.Arrays;
class GFG {
  
static void sortUsingHash(int a[], int n)
{
    // find the maximum element
    int max = Arrays.stream(a).max().getAsInt();
    int min = Math.abs(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[Math.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] > 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, 7,
                        5, 4, 3, 2, 1, 0 };
    int n = a.length;
    sortUsingHash(a, n);
}
}
  
// This code has been contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to sort an array using hash 
// function with negative values allowed. 
using System;
using System.Linq;
  
class GFG 
  
static void sortUsingHash(int []a, int n) 
    // find the maximum element 
    int max = a.Max(); 
    int min = Math.Abs(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[Math.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] > 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 */

chevron_right


Output:

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

Complexity:
This sort function can have complexity O(max_element). So performance depends on that set of data provided.

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)



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.