Loading

Paste #p1xjx4tqv

  1. /**
  2.  * Type safe Gnome Sort.
  3.  *
  4.  * This is a slightly modified Gnome search. The basic
  5.  * Gnome search tries to sort already sorted list parts.
  6.  * The modification skips these.
  7.  *
  8.  * @note Use this sort for presorted / regular sorted data.
  9.  *
  10.  * @param base Pointer to the first element of the array to be sorted.
  11.  * @param num Number of elements in the array pointed by base.
  12.  * @param comparator Function that compares two elements.
  13.  * @param desc Sort descending.
  14.  */
  15. template <typename T>
  16. static inline void GSortT(T *base, uint num, int (CDECL *comparator)(const T*, const T*), bool desc = false)
  17. {
  18.     if (num < 2) return;
  19.  
  20.     assert(base != NULL);
  21.     assert(comparator != NULL);
  22.  
  23.     T *a = base;
  24.     T *b = base + 1;
  25.     uint offset = 0;
  26.  
  27.     while (num > 1) {
  28.         const int diff = comparator(a, b);
  29.         if ((!desc && diff <= 0) || (desc && diff >= 0)) {
  30.             if (offset != 0) {
  31.                 /* Jump back to the last direction switch point */
  32.                 a += offset;
  33.                 b += offset;
  34.                 offset = 0;
  35.                 continue;
  36.             }
  37.  
  38.             a++;
  39.             b++;
  40.             num--;
  41.         } else {
  42.             Swap(*a, *b);
  43.  
  44.             if (a == base) continue;
  45.  
  46.             a--;
  47.             b--;
  48.             offset++;
  49.         }
  50.     }
  51. }

Version history

Revision # Author Created at
pxwjx24zl Anonymous 02 Nov 2017, 18:38:43 UTC Diff

Comments