70 const BufIter workingMiddle = std::move(begin, middle, workingBegin);
71 const BufIter workingEnd = std::move(middle, end, workingMiddle);
74 BufIter workingLeft = workingBegin;
75 BufIter workingRight = workingMiddle;
77 while (workingLeft != workingMiddle && workingRight != workingEnd) {
81 *output++ = !comp(*workingRight, *workingLeft) ? std::move(*workingLeft++) : std::move(*workingRight++);
84 std::move(workingLeft, workingMiddle, output);
85 std::move(workingRight, workingEnd, output);
213void peeksort(Iter begin, Iter end, Comparator comp = {})
215 auto length = std::distance(begin, end);
224 if (comp(*--end, *begin))
225 std::swap(*begin, *end);
229 using ValueType = std::iter_value_t<Iter>;
230 auto workingBuffer = std::vector<ValueType>(length);
238 auto peeksortImpl = [&workingBuffer,
239 &comp](
auto & peeksortImpl, Iter begin, Iter end, Iter leftRunEnd, Iter rightRunBegin) {
240 if (leftRunEnd == end || rightRunBegin == begin)
247 static constexpr std::size_t insertionsortThreshold = 16;
248 size_t length = std::distance(begin, end);
249 if (length <= insertionsortThreshold)
252 Iter middle = std::next(begin, (length / 2));
254 if (middle <= leftRunEnd) {
256 peeksortImpl(peeksortImpl, leftRunEnd, end, std::next(leftRunEnd), rightRunBegin);
259 }
else if (middle >= rightRunBegin) {
261 peeksortImpl(peeksortImpl, begin, rightRunBegin, leftRunEnd, std::prev(rightRunBegin));
269 if (!comp(*middle, *std::prev(middle)) ) {
278 if (i == begin && j == end)
281 if (middle - i < j - middle) {
283 peeksortImpl(peeksortImpl, begin, i, leftRunEnd, std::prev(i));
284 peeksortImpl(peeksortImpl, i, end, j, rightRunBegin);
288 peeksortImpl(peeksortImpl, begin, j, leftRunEnd, i);
289 peeksortImpl(peeksortImpl, j, end, std::next(j), rightRunBegin);
294 peeksortImpl(peeksortImpl, begin, end, begin, end);