LazyShpee

Counting sort

Dec 15th, 2015
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /* list, number of elements, minimum value in list, maximum value un list */
  5. void counting_sort_mm(int *list, int n, int min, int max)
  6. {
  7.   int i, j, z;
  8.  
  9.   int range = max - min + 1;
  10.   int *count = malloc(range * sizeof(*list));
  11.  
  12.   for(i = 0; i < range; i++) count[i] = 0;
  13.   for(i = 0; i < n; i++) count[ list[i] - min ]++;
  14.   for(i = min, z = 0; i <= max; i++) {
  15.     for(j = 0; j < count[i - min]; j++) {
  16.       list[z++] = i;
  17.     }
  18.   }
  19.   free(count);
  20. }
  21.  
  22. /* list, number of elements */
  23. void counting_sort(int *list, int n)
  24. {
  25.   int i, min, max;
  26.  
  27.   min = max = list[0];
  28.   for(i=1; i < n; i++) {
  29.     if ( list[i] < min ) {
  30.       min = list[i];
  31.     } else if ( list[i] > max ) {
  32.       max = list[i];
  33.     }
  34.   }
  35.   counting_sort_mm(list, n, min, max);
  36. }
Advertisement
Add Comment
Please, Sign In to add comment