Ladies_Man

#SORT__Heapsort Пирамидальная / Куча ;)

Dec 15th, 2013
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char str[22][22];
  6.  
  7. int compare(const void *a, const void *b)
  8. {
  9.     int i, count_a = 0, count_b = 0;
  10.     for (i = 0; i < strlen(a); i++) if ( ((char*)a)[i] == 'a' ) count_a++;
  11.  
  12.     for (i = 0; i < strlen(b); i++) if ( ((char*)b)[i] == 'a') count_b++;
  13.  
  14.     if (count_a == count_b) return 0;
  15.     return count_a > count_b ? 1 : -1;
  16. }
  17.  
  18. void swap(int a, int b, void *base, int nel, size_t width)
  19. {
  20.     memcpy (((void*)base + width*nel + width*22), base + width*a, width);
  21.     memcpy (base + width*a, base + width*b, width);
  22.     memcpy (base + width*b, ((void*)base + width*nel + width*22), width);
  23. }
  24.  
  25. void siftdown (int num_of_heap, void *base, size_t nel, size_t width)
  26. {
  27.     int child = num_of_heap*2, max = num_of_heap;
  28.  
  29.     if ((child < nel) && (compare(base + width*child, base + width*max) > 0))
  30.         max = child;
  31.     child++;
  32.     if ((child < nel) && (compare(base + width*child, base + width*max) > 0))
  33.         max = child;
  34.     if (max == num_of_heap) return;
  35.  
  36.     swap(num_of_heap, max, base, nel, width);
  37.     siftdown(max, base, nel, width);
  38. }
  39.  
  40. void heapsort(void *base, size_t nel, size_t width, int (*compare)(const void *a, const void *b))
  41. {
  42.     int i = nel / 2;
  43.  
  44.     for (i; i >= 0; i--) siftdown (i, base, nel, width);
  45.     nel--;
  46.     for ( ; nel > 0; --nel) {
  47.         swap (0, nel, base, nel, width);
  48.         siftdown (0, base, nel, width);
  49.     }
  50. }
  51.  
  52. int main()
  53. {
  54.     int i, n;
  55.     scanf("%d ", &n);
  56.     for (i = 0; i < n; i++) gets(str[i]);
  57.  
  58.     //if (n == 1) goto exit_no_sort;
  59.  
  60.     size_t width = 22*sizeof(char);
  61.     heapsort (str, n, width, compare);
  62.  
  63.     exit_no_sort:
  64.     for (i = 0; i < n; i++) printf("%s\n", str[i]);
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment