|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Map; |
| 3 | +import java.util.TreeMap; |
| 4 | + |
| 5 | +/** |
| 6 | + * |
| 7 | + * @author Youssef Ali (https://github.com/youssefAli11997) |
| 8 | + * |
| 9 | + */ |
| 10 | + |
| 11 | +class CountingSort { |
| 12 | + |
| 13 | + /** |
| 14 | + * This method implements the Generic Counting Sort |
| 15 | + * |
| 16 | + * @param array The array to be sorted |
| 17 | + * @param last The count of total number of elements in array |
| 18 | + * Sorts the array in increasing order |
| 19 | + * It uses array elements as keys in the frequency map |
| 20 | + **/ |
| 21 | + |
| 22 | + public static <T extends Comparable<T>> void CS(T[] array, int last) { |
| 23 | + |
| 24 | + Map<T, Integer> frequency = new TreeMap<T, Integer>(); |
| 25 | + // The final output array |
| 26 | + ArrayList<T> sortedArray = new ArrayList<T>(); |
| 27 | + |
| 28 | + // Counting the frequency of @param array elements |
| 29 | + for(T t : array) { |
| 30 | + try{ |
| 31 | + frequency.put(t, frequency.get(t)+1); |
| 32 | + }catch(Exception e){ // new entry |
| 33 | + frequency.put(t, 1); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // Filling the sortedArray |
| 38 | + for(Map.Entry<T, Integer> element : frequency.entrySet()) { |
| 39 | + for(int j=0; j<element.getValue(); j++) |
| 40 | + sortedArray.add(element.getKey()); |
| 41 | + } |
| 42 | + |
| 43 | + for(int i=0; i<array.length; i++){ |
| 44 | + array[i] = sortedArray.get(i); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Driver Program |
| 49 | + public static void main(String[] args) { |
| 50 | + // Integer Input |
| 51 | + Integer[] arr1 = {4,23,6,78,1,54,231,9,12}; |
| 52 | + int last = arr1.length; |
| 53 | + |
| 54 | + System.out.println("Before Sorting:"); |
| 55 | + for (int i=0;i<arr1.length;i++) { |
| 56 | + System.out.print(arr1[i] + " "); |
| 57 | + } |
| 58 | + System.out.println(); |
| 59 | + |
| 60 | + CS(arr1, last); |
| 61 | + |
| 62 | + // Output => 1 4 6 9 12 23 54 78 231 |
| 63 | + System.out.println("After Sorting:"); |
| 64 | + for (int i=0;i<arr1.length;i++) { |
| 65 | + System.out.print(arr1[i] + " "); |
| 66 | + } |
| 67 | + System.out.println(); |
| 68 | + |
| 69 | + System.out.println("------------------------------"); |
| 70 | + |
| 71 | + // String Input |
| 72 | + String[] array1 = {"c", "a", "e", "b","d"}; |
| 73 | + last = array1.length; |
| 74 | + |
| 75 | + System.out.println("Before Sorting:"); |
| 76 | + for (int i=0;i<array1.length;i++) { |
| 77 | + System.out.print(array1[i] + " "); |
| 78 | + } |
| 79 | + System.out.println(); |
| 80 | + |
| 81 | + CS(array1, last); |
| 82 | + |
| 83 | + //Output => a b c d e |
| 84 | + System.out.println("After Sorting:"); |
| 85 | + for(int i=0; i<last; i++) { |
| 86 | + System.out.print(array1[i]+" "); |
| 87 | + } |
| 88 | + |
| 89 | + } |
| 90 | +} |
0 commit comments