Java Program for Counting Sort

JavaObject Oriented ProgrammingProgramming

The Counting Sort counts the number of objects having distinct key values. Let us see an example −

Note − The below code can be used with negative numbers as well.

Example

 Live Demo

import java.util.*;
public class Demo{
   static void count_sort(int[] arr){
      int max_val = Arrays.stream(arr).max().getAsInt();
      int min_val = Arrays.stream(arr).min().getAsInt();
      int range = max_val - min_val + 1;
      int count[] = new int[range];
      int result[] = new int[arr.length];
      for (int i = 0; i < arr.length; i++){
         count[arr[i] - min_val]++;
      }
      for (int i = 1; i < count.length; i++){
         count[i] += count[i - 1];
      }
      for (int i = arr.length - 1; i >= 0; i--){
         result[count[arr[i] - min_val] - 1] = arr[i];
         count[arr[i] - min_val]--;
      }
      for (int i = 0; i < arr.length; i++){
         arr[i] = result[i];
      }
   }
   static void printVal(int[] arr){
      for (int i = 0; i < arr.length; i++){
         System.out.print(arr[i] + " ");
      }  
      System.out.println("");
   }
   public static void main(String[] args){
      int[] arr = {-5, 0, -3, 8, 34, 56, 89, -11, -95, -1, 10};
      System.out.println("The array contains");
      for (int i = 0; i < arr.length; i++){
         System.out.print(arr[i] + " ");
      }
      System.out.println();
      System.out.println("Implementing Counting Sort in Java results in : ");
      count_sort(arr);
      printVal(arr);
   }  
}

Output

The array contains
-5 0 -3 8 34 56 89 -11 -95 -1 10
Implementing Counting Sort in Java results in :
-95 -11 -5 -3 -1 0 8 10 34 56 89

A class named Demo contains the ‘count_sort’ function. Here, the array is iterated over and the count value is increment.

Next, this count array is iterated over and previous value is assigned to the next value. The array is iterated over again and the element of the array is assigned to the result array and the count array is decremented. Then, the array is iterated over again and the elements in the result array is assigned to the array. A print function is defined that prints the data on the console. The main function defines the elements of the array and calls the count sort on these elements.

raja
Published on 04-Jul-2020 09:38:17
Advertisements