Jacob_Thomas

Count sort

Jan 28th, 2021
704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.util.*;
  2. class CountSort{
  3.     public static void main(String args[]){
  4.         System.out.println("Enter the size of array");
  5.         Scanner sc = new Scanner(System.in);
  6.         int len = sc.nextInt();
  7.         int a[] = new int[len];
  8.         int largest = 0;
  9.         System.out.println("Enter the array");
  10.         for(int x = 0; x<len; x++){
  11.             a[x] = sc.nextInt();
  12.             if(a[x] > largest){
  13.                 largest = a[x];
  14.             }
  15.         }
  16.        
  17.         int b[] = new int[largest+1];
  18.         Arrays.fill(b, 0);
  19.        
  20.         for(int x = 0; x<len; x++){
  21.             b[a[x]] += 1;
  22.         }
  23.         System.out.print("\nFrequencies of the array\n");
  24.         System.out.println(Arrays.toString(b));
  25.        
  26.         int c[] = new int[len];
  27.        
  28.        
  29.         /*
  30.            Here starts the different approach, ie fill the new array c with the number of times a number appears
  31.            in the frequency array b. Example is 0 appears 2 times in b then put 2 0s in c and move on.
  32.            */
  33.         int index = 0;
  34.         int value;
  35.         for(int x = 0; x<largest+1; x++){
  36.             value = b[x];
  37.             if(value == 0){
  38.                 continue;
  39.             }
  40.             else{
  41.                 while(value > 0){
  42.                     c[index] = x;
  43.                     index += 1;
  44.                     value -= 1;
  45.                 }
  46.             }
  47.         }
  48.         System.out.print("\nSorted array\n");
  49.         System.out.println(Arrays.toString(c));
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment