| 2 | import java.util.Scanner; |
| 3 | |
| 4 | public class CountSort { |
| 5 | |
| 6 | public static void main(String[] args) { |
| 7 | |
| 8 | // This algorithm is preferred for single digit number |
| 9 | System.out.println("Counting Sort : "); |
| 10 | |
| 11 | System.out.print("Enter the size of array : "); |
| 12 | try (Scanner sc = new Scanner(System.in)) { |
| 13 | int n = sc.nextInt(); |
| 14 | int a[] = new int[n]; |
| 15 | |
| 16 | System.out.println("Enter elements : "); |
| 17 | for (int i = 0; i < n; i++) { |
| 18 | a[i] = sc.nextInt(); |
| 19 | } |
| 20 | |
| 21 | System.out.println("Array before sorting : " + Arrays.toString(a)); |
| 22 | |
| 23 | countSort(a); // calling the function |
| 24 | |
| 25 | System.out.println("\nArray after sorting : " + Arrays.toString(a)); |
| 26 | } |
| 27 | |
| 28 | // Time Complexity : O(n+k+n+n) = O(n+k) |
| 29 | // if we consider k as content then O(n) -> Linear Time :) |
| 30 | // Space Complexity : O(n+k) |
| 31 | } |
| 32 | |
| 33 | private static void countSort(int a[]) { |
| 34 | int k = getMax(a); // to get maximum element for making count array |
| 35 | |
| 36 | int count[] = new int[k + 1]; // to fill frequency of element |
| 37 | for (int i = 0; i < a.length; i++) { |
| 38 | count[a[i]]++; |
| 39 | } |
| 40 | |
| 41 | // to reflect position in count array |
| 42 | // similar to filling cumulative frequency |
| 43 | for (int i = 1; i <= k; i++) { |
| 44 | count[i] = count[i] + count[i - 1]; |
| 45 | } |
| 46 | |
| 47 | // to put element at it's correct position |
| 48 | int b[] = new int[a.length]; |
| 49 | for (int i = b.length - 1; i >= 0; i--) { |
| 50 | b[--count[a[i]]] = a[i]; |
| 51 | } |
| 52 | |
| 53 | // copying elements to a |
| 54 | for (int i = 0; i < a.length; i++) |
| 55 | a[i] = b[i]; |
| 56 | } |
| 57 | |
| 58 | private static int getMax(int[] a) { |
| 59 | int max = Integer.MIN_VALUE; |
| 60 | for (int i : a) { |
| 61 | if (i > max) |
nothing calls this directly
no outgoing calls
no test coverage detected