×

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

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.