diff --git a/Sorts/CountingSort.java b/Sorts/CountingSort.java new file mode 100644 index 00000000..e6828265 --- /dev/null +++ b/Sorts/CountingSort.java @@ -0,0 +1,90 @@ +import java.util.ArrayList; +import java.util.Map; +import java.util.TreeMap; + +/** + * + * @author Youssef Ali (https://github.com/youssefAli11997) + * + */ + +class CountingSort { + + /** + * This method implements the Generic Counting Sort + * + * @param array The array to be sorted + * @param last The count of total number of elements in array + * Sorts the array in increasing order + * It uses array elements as keys in the frequency map + **/ + + public static > void CS(T[] array, int last) { + + Map frequency = new TreeMap(); + // The final output array + ArrayList sortedArray = new ArrayList(); + + // Counting the frequency of @param array elements + for(T t : array) { + try{ + frequency.put(t, frequency.get(t)+1); + }catch(Exception e){ // new entry + frequency.put(t, 1); + } + } + + // Filling the sortedArray + for(Map.Entry element : frequency.entrySet()) { + for(int j=0; j 1 4 6 9 12 23 54 78 231 + System.out.println("After Sorting:"); + for (int i=0;i a b c d e + System.out.println("After Sorting:"); + for(int i=0; i