×

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array, and the auxiliary array's index is mapped to the count to do the sorting.

Implementing Counting Sort

  • Find the largest element (let's call it max) in the provided array.
Counting sort in Java
  • Make an array with a length of max+1 and all of its items set to 0. The number of elements in the array is kept in this array for counting purposes.
Counting sort in Java
  • Adjust the index of each element's count inside the count array.
    For instance, if such count for element 3 is 2, then 2 is placed in the third position of said count array. If element "5" in the array is absent, 0 is kept at the fifth position.
Counting sort in Java
  • Count array elements' cumulative sums should be stored. It makes it easier to insert the elements at the proper index in the sorted array.
Counting sort in Java
  • In the count array, determine the index of each original array element. This provides the total count. Put the element where the index was determined, as illustrated in the following diagram.
Counting sort in Java
  • Once you've positioned each element correctly, deduct one from its count.

Counting sort Algorithm

countingSort(array, size)
max <- find the biggest component of an array
Set the count array to zeroes.
for j <- 0 to size
discover the total number of each distinct element, and then store that number at the jth index in the count array.
for i <- 1 to max
 Find the total and save it directly in the count array.
for j <- size down to 1
 return the array's elements
  reduce the count of each element that has been restored by 1

Java Counting sort Program

CountingSortExpl.java

import java.util.Arrays;
class CountingSortExpl {
void countSort(int a[], int s) {
int[] output = new int[s + 1];
// Determine the array's greatest element
int max = a[0];
for (int i = 1; i < s; i++) {
if (a[i] > max)
   max = a[i];
} int[] count = new int[max + 1];
 // Set up the count array with nothing but zeros
for (int i = 0; i < max; ++i) {
 count[i] = 0;
}
// Save the total number of each element.
for (int i = 0; i < s; i++) {
count[a[i]]++;
}
// Keep track of each array's cumulative count.
for (int i = 1; i <= max; i++) {
count[i] += count[i - 1];
}
// Place the members of the output array in the count array by finding the index 
// of each original array element.
for (int i = s - 1; i >= 0; i--) {
output[count[a[i]] - 1] = a[i];
     count[a[i]]--;
}
// Transform the sorted items into the initial array.
for (int i = 0; i < s; i++) {
a[i] = output[i];
}
}
public static void main(String args[]) {
int[] d = { 8, 2, 3, 4, 1, 3, 2 };
int s = d.length;
  CountingSortExpl c = new CountingSortExpl();
  c.countSort(d, s);
  System.out.println(" Ascending Order Sorted Array: ");
   System.out.println(Arrays.toString(d));
}
}

Output:

Counting sort in Java

Complexity

Time complexity        

BestO(n+k)
WorstO(n+k)
AverageO(n+k)

Space Complexity

The space complexity is O(max).

Applications of Counting sort

One uses a counting sort when:

  • Smaller numbers can have several counts.
  • The requirement is linear complexity.

Related Topics

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.