diff --git a/src/counting_sort_demo.cpp b/src/counting_sort_demo.cpp new file mode 100644 index 00000000..508675c3 --- /dev/null +++ b/src/counting_sort_demo.cpp @@ -0,0 +1,135 @@ +/* +Author : Aswin Sampath +Topic : Counting Sort + + Counting Sort + When to use? + Vizualise the array/vector elements + Amount of space needed by the algorithm = Range of the vector + Range of vector = Max(vector)- Min(vector) + If Range is of the order 10^5 then we can use counting sort subjet to the compiler + + How to Implement + Sort the numbers according to their frequency/ number of occurences + Place the element in their respective position according to the ranking + + Time Complexity : O(n) + Space COmplexity : O(Max(arr)-Min(arr)); +*/ + + +#include +#include +using namespace std; + +void printVector(vectorv){ + cout<<"\n Vector elements \n "; + for(int element:v){ + cout<arr){ + int minele = arr[0]; + for(int ele:arr){ + if(ele<=minele)minele=ele; + } + return minele; +} + +int findMax(vectorarr){ + int maxele = arr[0]; + for(int ele:arr){ + if(ele>=maxele)maxele=ele; + } + return maxele; +} + + +int findRange(vectorarr){ + int maxele = findMax(arr); + int minele = findMin(arr); + return maxele - minele; +} + +vectorfreq; +vectoroutput; + +void countingSort(vector &arr,int range){ + + // cout<<"Size of arr = "<arr = {2,3,7,4,6,8,9,2,5,4,8,3,1,6,7,2,5,7,6,1,4,2,3,9,8,7,4,5,6,0}; + + /* Frequency Table + ele freq + 0 - 1 + 1 - 2 + 2 - 4 + 3 - 3 + 4 - 4 + 5 - 3 + 6 - 4 + 7 - 4 + 8 - 3 + 9 - 2 + */ + + // Vector Range = max(arr)-min(arr) = 9 - 0 = 9 Hence we require of a 9 space in frequency array + int range = findRange(arr); + cout<<"Before Sorting \n"; + printVector(arr); + countingSort(arr,range); // Sorting algorithm + cout<<"After Sorting \n"; + printVector(arr); +} +