|
32 | 32 | }
|
33 | 33 |
|
34 | 34 | // sub-macro that merges two sub-sorted arrays [start, ..., mid), [mid, ..., end) together
|
35 |
| -#define _mjMERGE(type, arr, buf, start, mid, end, cmp, context) \ |
| 35 | +#define _mjMERGE(type, src, dest, start, mid, end, cmp, context) \ |
36 | 36 | { \
|
37 |
| - int len1 = mid - start, len2 = end - mid; \ |
38 |
| - type* left = buf, *right = buf + len1; \ |
39 |
| - for (int i = 0; i < len1; i++) left[i] = arr[start + i]; \ |
40 |
| - for (int i = 0; i < len2; i++) right[i] = arr[mid + i]; \ |
41 |
| - int i = 0, j = 0, k = start; \ |
42 |
| - while (i < len1 && j < len2) { \ |
43 |
| - if (cmp(left + i, right + j, context) <= 0) { \ |
44 |
| - arr[k++] = left[i++]; \ |
| 37 | + int i = start, j = mid, k = start; \ |
| 38 | + while (i < mid && j < end) { \ |
| 39 | + if (cmp(src + i, src + j, context) <= 0) { \ |
| 40 | + dest[k++] = src[i++]; \ |
45 | 41 | } else { \
|
46 |
| - arr[k++] = right[j++]; \ |
| 42 | + dest[k++] = src[j++]; \ |
47 | 43 | } \
|
48 | 44 | } \
|
49 |
| - while (i < len1) arr[k++] = left[i++]; \ |
50 |
| - while (j < len2) arr[k++] = right[j++]; \ |
| 45 | + if (i < mid) memcpy(dest + k, src + i, (mid - i) * sizeof(type)); \ |
| 46 | + else if (j < end) memcpy(dest + k, src + j, (end - j) * sizeof(type)); \ |
51 | 47 | }
|
52 | 48 |
|
53 | 49 | // defines an inline stable sorting function via tiled merge sorting (timsort)
|
|
60 | 56 | int end = (start + _mjRUNSIZE < n) ? start + _mjRUNSIZE : n; \
|
61 | 57 | _mjINSERTION_SORT(type, arr, start, end, cmp, context); \
|
62 | 58 | } \
|
| 59 | + type* src = arr, *dest = buf, *tmp; \ |
63 | 60 | for (int len = _mjRUNSIZE; len < n; len *= 2) { \
|
64 | 61 | for (int start = 0; start < n; start += 2*len) { \
|
65 | 62 | int mid = start + len; \
|
66 | 63 | int end = (start + 2*len < n) ? start + 2*len : n; \
|
67 | 64 | if (mid < end) { \
|
68 |
| - _mjMERGE(type, arr, buf, start, mid, end, cmp, context); \ |
| 65 | + _mjMERGE(type, src, dest, start, mid, end, cmp, context); \ |
| 66 | + } else { \ |
| 67 | + memcpy(dest + start, src + start, (end - start) * sizeof(type)); \ |
69 | 68 | } \
|
70 | 69 | } \
|
| 70 | + tmp = src; src = dest; dest = tmp; \ |
71 | 71 | } \
|
| 72 | + if (src != arr) memcpy(arr, src, n * sizeof(type)); \ |
72 | 73 | }
|
73 | 74 |
|
74 | 75 | #endif // MUJOCO_SRC_ENGINE_ENGINE_SORT_H_
|
0 commit comments