| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#pragma once |
| 6 |
|
| 7 |
JPH_NAMESPACE_BEGIN |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
template <typename Iterator, typename Pred> |
| 14 |
void BinaryHeapPush(Iterator inBegin, Iterator inEnd, Pred inPred) |
| 15 |
{ |
| 16 |
using diff_t = typename std::iterator_traits<Iterator>::difference_type; |
| 17 |
using elem_t = typename std::iterator_traits<Iterator>::value_type; |
| 18 |
|
| 19 |
|
| 20 |
diff_t count = std::distance(inBegin, inEnd); |
| 21 |
|
| 22 |
|
| 23 |
diff_t current = count - 1; |
| 24 |
while (current > 0) |
| 25 |
{ |
| 26 |
|
| 27 |
elem_t ¤t_elem = *(inBegin + current); |
| 28 |
|
| 29 |
|
| 30 |
diff_t parent = (current - 1) >> 1; |
| 31 |
elem_t &parent_elem = *(inBegin + parent); |
| 32 |
|
| 33 |
|
| 34 |
if (inPred(parent_elem, current_elem)) |
| 35 |
{ |
| 36 |
std::swap(parent_elem, current_elem); |
| 37 |
current = parent; |
| 38 |
} |
| 39 |
else |
| 40 |
{ |
| 41 |
|
| 42 |
break; |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
template <typename Iterator, typename Pred> |
| 52 |
void BinaryHeapPop(Iterator inBegin, Iterator inEnd, Pred inPred) |
| 53 |
{ |
| 54 |
using diff_t = typename std::iterator_traits<Iterator>::difference_type; |
| 55 |
|
| 56 |
|
| 57 |
std::swap(*(inEnd - 1), *inBegin); |
| 58 |
|
| 59 |
|
| 60 |
diff_t count = std::distance(inBegin, inEnd) - 1; |
| 61 |
|
| 62 |
|
| 63 |
diff_t largest = 0; |
| 64 |
for (;;) |
| 65 |
{ |
| 66 |
|
| 67 |
diff_t child = (largest << 1) + 1; |
| 68 |
|
| 69 |
|
| 70 |
if (child >= count) |
| 71 |
break; |
| 72 |
|
| 73 |
|
| 74 |
diff_t prev_largest = largest; |
| 75 |
|
| 76 |
|
| 77 |
if (inPred(*(inBegin + largest), *(inBegin + child))) |
| 78 |
largest = child; |
| 79 |
|
| 80 |
|
| 81 |
++child; |
| 82 |
|
| 83 |
|
| 84 |
if (child < count && inPred(*(inBegin + largest), *(inBegin + child))) |
| 85 |
largest = child; |
| 86 |
|
| 87 |
|
| 88 |
if (prev_largest == largest) |
| 89 |
break; |
| 90 |
|
| 91 |
|
| 92 |
std::swap(*(inBegin + prev_largest), *(inBegin + largest)); |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
JPH_NAMESPACE_END |