4 /** is only ever called for i1 < i2 */
5 typedef void (int i1, int i2, entity pass) swapfunc_t;
6 /** <0 for <, ==0 for ==, >0 for > (like strcmp) */
7 typedef int (int i1, int i2, entity pass) comparefunc_t;
9 void heapsort(int n, swapfunc_t swap, comparefunc_t cmp, entity pass)
11 #define heapify(_count) \
14 for (int start = floor(((_count) - 2) / 2); start >= 0; --start) \
16 siftdown(start, (_count) - 1); \
21 #define siftdown(_start, _end) \
24 for (int root = (_start); root * 2 + 1 <= (_end); ) \
26 int child = root * 2 + 1; \
27 if (child < (_end) && cmp(child, child + 1, pass) < 0) child += 1; \
28 if (cmp(root, child, pass) >= 0) break; \
29 swap(root, child, pass); \
45 void shuffle(float n, swapfunc_t swap, entity pass)
47 for (int i = 1; i < n; ++i)
49 // swap i-th item at a random position from 0 to i
50 // proof for even distribution:
53 // item n+1 gets at any position with chance 1/(n+1)
54 // all others will get their 1/n chance reduced by factor n/(n+1)
55 // to be on place n+1, their chance will be 1/(n+1)
56 // 1/n * n/(n+1) = 1/(n+1)
58 int j = floor(random() * (i + 1));
59 if (j != i) swap(j, i, pass);