| 3 | //Problem : Counting Sort |
| 4 | |
| 5 | public class CountingSort { |
| 6 | public static void countingSort(int arr[]) { |
| 7 | int largest = Integer.MIN_VALUE; |
| 8 | for(int i=0; i<arr.length; i++) { |
| 9 | largest = Math.max(largest, arr[i]); |
| 10 | } |
| 11 | |
| 12 | int count[] = new int[largest+1]; |
| 13 | for(int i=0; i<arr.length; i++) { |
| 14 | count[arr[i]]++; |
| 15 | } |
| 16 | int j = 0; |
| 17 | for(int i=0; i<count.length; i++) { |
| 18 | while(count[i] > 0) { |
| 19 | arr[j] = i; |
| 20 | j++; |
| 21 | count[i]--; |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | public static void countingSortDescending(int arr[]) { |
| 27 | int largest = Integer.MIN_VALUE; |
| 28 | for(int i=0; i<arr.length; i++) { |
| 29 | largest = Math.max(largest, arr[i]); |
| 30 | } |
| 31 | |
| 32 | int count[] = new int[largest+1]; |
| 33 | for(int i=0; i<arr.length; i++) { |
| 34 | count[arr[i]]++; |
| 35 | } |
| 36 | int j = 0; |
| 37 | for(int i=count.length-1; i>=0; i--) { |
| 38 | while(count[i] > 0) { |
| 39 | arr[j] = i; |
| 40 | j++; |
| 41 | count[i]--; |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | public static void printArr(int arr[]) { |
| 47 | for(int i=0; i<arr.length; i++) { |
| 48 | System.out.print(arr[i]+" "); |
| 49 | } |
| 50 | System.out.println(); |
| 51 | } |
| 52 | |
| 53 | public static void main(String args[]) { |
| 54 | int arr[] = {1, 4, 1, 3, 2, 4, 3, 7}; |
| 55 | countingSortDescending(arr); |
| 56 | printArr(arr); |
| 57 | } |
| 58 | } |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…