fork download
  1. #include <stdio.h>
  2.  
  3. #define ARRAYSIZE 6
  4. #define MAX 4
  5.  
  6. int main()
  7. {
  8. int arr[] = {2, 1, 3, 2, 1, 4};
  9. int final[ARRAYSIZE];
  10.  
  11. // Given we know max element in array
  12. // This technique is based on counting sort
  13. int count[MAX + 1] = {0};
  14. int i = 0;
  15. int j = 0;
  16.  
  17. for (i = 0; i < ARRAYSIZE; i++) {
  18. count[arr[i]]++;
  19. }
  20.  
  21. for (i = 0; i < MAX + 1; i++) {
  22. if (count[i] != 0) {
  23. while (count[i] != 0) {
  24. final[j++] = i;
  25. count[i]--;
  26. }
  27. }
  28. }
  29.  
  30. printf("Sorted Array\n");
  31. for (i = 0; i < ARRAYSIZE; i++) {
  32. printf("%d ", final[i]);
  33. }
  34.  
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
Sorted Array
1 1 2 2 3 4