fork(3) download
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <algorithm>
  5.  
  6. void basic_count_sort(int * arr, int size) {
  7. // Find the largest element in our array
  8. int max = *std::max_element(arr, arr+size);
  9.  
  10. // Make an array of that size, to store frequency of each element
  11. int * count = new int[max+1];
  12.  
  13. //Initialize array to 0
  14. std::fill(count, count+max+1, 0);
  15.  
  16. for(int i=0;i<size;++i) {
  17. ++count[arr[i]];
  18. }
  19.  
  20. int currPos = 0;
  21. for(int i=0;i<max+1;++i) {
  22. if(count[i] != 0) {
  23. // Fill array with i, count[i] times
  24. // From array indices pos to pos+count[i]
  25. std::fill(arr + currPos, arr + currPos + count[i], i);
  26. currPos += count[i];
  27. }
  28. }
  29. }
  30.  
  31. int main() {
  32. int arr[] = {100,100,100,5,3,3,6,5,4,2,4,5,5,4,2,1,1,1,100,1};
  33. int size = 20;
  34. basic_count_sort(arr, size);
  35. for(int i=0;i<size;++i)
  36. std::cout << arr[i] << " ";
  37. }
  38.  
Success #stdin #stdout 0.01s 2812KB
stdin
Standard input is empty
stdout
1 1 1 1 2 2 3 3 4 4 4 5 5 5 5 6 100 100 100 100