Sorting using trivial hash function
Last Updated :
19 Apr, 2023
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, 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
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>
Output0 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,
7, 5, 4, 3, 2, 1, 0 };
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:
- Can only sort array elements of limited range (typically from -10^6 to +10^6)
- Auxiliary space in worst cases is O(max_element) + O(min_element)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem