Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2014
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <stddef.h>
  4. #include <string.h>
  5. #include "Sort.h"
  6.  
  7. /// \brief Меняет местами 2 элемента массива.
  8. /// \param[in] e1 - Элемент 1
  9. /// \param[in] e2 - Элемент 2
  10. void swap(size_t size, char *e1, char *e2)
  11. {
  12.     char *o = malloc(size); // Промежуточное значение
  13.     if (o)
  14.     {
  15.         memmove(o, e1, size);
  16.         memmove(e1, e2, size);
  17.         memmove(e2, o, size);
  18.         free(o);
  19.     }
  20. }
  21.  
  22. /// \brief Сортировка.
  23. /// \details Модифицированная сортировка пузырьком I.
  24. /// \param[in] buf -Адрес первого элемента массива
  25. /// \param[in] num - Число элементов
  26. /// \param[in] size - Размер элемента
  27. /// \param[in] sr_name - Функция сравнения
  28. void mysort(void *buf, size_t num, size_t size, int (*sr_name) (const void *, const void *))
  29. {
  30.     char *pa, *pb; // Указатели
  31.     int f, h; // Флаги остановки
  32.     int i, j; // Счетчики
  33.  
  34.    
  35.     char *fr = malloc(size * num);
  36.     memmove(fr, buf, num*size);
  37.     h = 0;
  38.     f = num - 1;
  39.     pa = fr + size;
  40.     pb = fr + 2*size;
  41.  
  42.     for (i = 0; i < num - f; ++i)
  43.     {
  44.         for (j = 0; j < f; ++j)
  45.         {
  46.             if((sr_name(pa, pb)) > 0)
  47.             {
  48.                 swap(size, pa, pb);
  49.                 h = j;
  50.             }
  51.             pa += size;
  52.             pb += size;
  53.         }
  54.         pa = fr + size;
  55.         pb = fr + 2 * size;
  56.         if (h != 0)
  57.         {
  58.             f = h;
  59.             h = 0;
  60.         }
  61.        
  62.     }
  63.    
  64.     free(buf); 
  65.     buf = fr;  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement