]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/sort.qh
2790cdf2dc3cc760dbe814bc8c8edb3be2322695
[xonotic/xonotic-data.pk3dir.git] / qcsrc / lib / sort.qh
1 #pragma once
2
3 /** is only ever called for i1 < i2 */
4 USING(swapfunc_t, void (int i1, int i2, entity pass));
5 /** <0 for <, ==0 for ==, >0 for > (like strcmp) */
6 USING(comparefunc_t, int (int i1, int i2, entity pass));
7
8 void heapsort(int n, swapfunc_t swap, comparefunc_t cmp, entity pass)
9 {
10         #define heapify(_count) \
11                 MACRO_BEGIN \
12                 { \
13                         for (int start = floor(((_count) - 2) / 2); start >= 0; --start) \
14                         { \
15                                 siftdown(start, (_count) - 1); \
16                         } \
17                 } MACRO_END
18
19         #define siftdown(_start, _end) \
20                 MACRO_BEGIN \
21                 { \
22                         for (int root = (_start); root * 2 + 1 <= (_end); ) \
23                         { \
24                                 int child = root * 2 + 1; \
25                                 if (child < (_end) && cmp(child, child + 1, pass) < 0) child += 1; \
26                                 if (cmp(root, child, pass) >= 0) break; \
27                                 swap(root, child, pass); \
28                                 root = child; \
29                         } \
30                 } MACRO_END
31
32         heapify(n);
33         int end = n - 1;
34         while (end > 0)
35         {
36                 swap(0, end, pass);
37                 end -= 1;
38                 siftdown(0, end);
39         }
40 }
41
42 void shuffle(float n, swapfunc_t swap, entity pass)
43 {
44         for (int i = 1; i < n; ++i)
45         {
46                 // swap i-th item at a random position from 0 to i
47                 // proof for even distribution:
48                 //   n = 1: obvious
49                 //   n -> n+1:
50                 //     item n+1 gets at any position with chance 1/(n+1)
51                 //     all others will get their 1/n chance reduced by factor n/(n+1)
52                 //     to be on place n+1, their chance will be 1/(n+1)
53                 //     1/n * n/(n+1) = 1/(n+1)
54                 //     q.e.d.
55                 int j = floor(random() * (i + 1));
56                 if (j != i) swap(j, i, pass);
57         }
58 }