Guest User

Untitled

a guest
Jul 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4.  
  5. int max(int* arr, int len) {
  6.  
  7. int out = arr[0];
  8. for (int i = 0; i < len; i++)
  9.  
  10. if (arr[i] > out)
  11. out = arr[i];
  12. return out;
  13. }
  14.  
  15. void sort(int** in, int** out, size_t length) {
  16. int* inputs = *in;
  17. int* outputs = *out;
  18.  
  19. // this is the size of the array of counts
  20. int greatest = max(inputs, length); // find the greatest number in the array
  21.  
  22. // allocate the array of counts
  23. int* counts = calloc(greatest + 1, sizeof(int));
  24.  
  25. // count numbers in input array
  26. for (int i = 0; i < length; i++) {
  27. counts[inputs[i]]++;
  28. }
  29.  
  30. int counter = 0; // keep track of where we are in output array
  31.  
  32. // loop through all the counts
  33. for (int i = 0; i < (greatest + 1); i++) { // for every count in array
  34. for (int j = 0; j < counts[i]; j++) { // loop that many times
  35. outputs[counter++] = i; // add the integer being counted to the output array
  36.  
  37. }
  38. }
  39. free(counts);
  40. }
  41.  
  42. int main(int argc, char** argv) {
  43. int *inputs, *outputs;
  44. size_t length = argc - 1; // number of integers to sort
  45.  
  46. inputs = malloc(sizeof(int) * (argc - 1));
  47. outputs = malloc(sizeof(int) * (argc - 1));
  48.  
  49. for (int i = 1; i < argc; i++) {
  50. inputs[i - 1] = atoi(argv[i]); // assign arguments to array
  51. }
  52.  
  53. sort(&inputs, &outputs, length);
  54.  
  55. for (size_t i = 0; i < (length); i++) {
  56. printf("%d ", outputs[i]); // print space separated sorted numbers
  57. }
  58. printf("n");
  59.  
  60. free(inputs);
  61. free(outputs);
  62.  
  63. return 0;
  64. }
Add Comment
Please, Sign In to add comment