Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
sort.hh
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <iterator>
5#include <concepts>
6#include <vector>
7#include <type_traits>
8#include <functional>
9
21
22/* PeekSort attribution:
23 *
24 * MIT License
25 *
26 * Copyright (c) 2022 Sebastian Wild
27 *
28 * Permission is hereby granted, free of charge, to any person obtaining a copy
29 * of this software and associated documentation files (the "Software"), to deal
30 * in the Software without restriction, including without limitation the rights
31 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
32 * copies of the Software, and to permit persons to whom the Software is
33 * furnished to do so, subject to the following conditions:
34 *
35 * The above copyright notice and this permission notice shall be included in all
36 * copies or substantial portions of the Software.
37 *
38 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44 * SOFTWARE.
45 */
46
47namespace nix {
48
64template<
65 std::forward_iterator Iter,
66 std::random_access_iterator BufIter,
67 typename Comparator = std::less<std::iter_value_t<Iter>>>
68void mergeSortedRunsInPlace(Iter begin, Iter middle, Iter end, BufIter workingBegin, Comparator comp = {})
69{
70 const BufIter workingMiddle = std::move(begin, middle, workingBegin);
71 const BufIter workingEnd = std::move(middle, end, workingMiddle);
72
73 Iter output = begin;
74 BufIter workingLeft = workingBegin;
75 BufIter workingRight = workingMiddle;
76
77 while (workingLeft != workingMiddle && workingRight != workingEnd) {
78 /* Note the inversion here !comp(...., ....). This is required for the merge to be stable.
79 If a == b where a if from the left part and b is the the right, then we have to pick
80 a. */
81 *output++ = !comp(*workingRight, *workingLeft) ? std::move(*workingLeft++) : std::move(*workingRight++);
82 }
83
84 std::move(workingLeft, workingMiddle, output);
85 std::move(workingRight, workingEnd, output);
86}
87
107template<std::bidirectional_iterator Iter, typename Comparator = std::less<std::iter_value_t<Iter>>>
108void insertionsort(Iter begin, Iter end, Comparator comp = {})
109{
110 if (begin == end)
111 return;
112 for (Iter current = std::next(begin); current != end; ++current) {
113 for (Iter insertionPoint = current;
114 insertionPoint != begin && comp(*insertionPoint, *std::prev(insertionPoint));
115 --insertionPoint) {
116 std::swap(*insertionPoint, *std::prev(insertionPoint));
117 }
118 }
119}
120
125template<std::forward_iterator Iter, typename Comparator = std::less<std::iter_value_t<Iter>>>
126Iter strictlyDecreasingPrefix(Iter begin, Iter end, const Comparator & comp = {})
127{
128 if (begin == end)
129 return begin;
130 while (std::next(begin) != end && /* *std::next(begin) < begin */
131 comp(*std::next(begin), *begin))
132 ++begin;
133 return std::next(begin);
134}
135
140template<std::bidirectional_iterator Iter, typename Comparator = std::less<std::iter_value_t<Iter>>>
141Iter strictlyDecreasingSuffix(Iter begin, Iter end, const Comparator & comp = {})
142{
143 if (begin == end)
144 return end;
145 while (std::prev(end) > begin && /* *std::prev(end) < *std::prev(end, 2) */
146 comp(*std::prev(end), *std::prev(end, 2)))
147 --end;
148 return std::prev(end);
149}
150
155template<std::bidirectional_iterator Iter, typename Comparator = std::less<std::iter_value_t<Iter>>>
156Iter weaklyIncreasingPrefix(Iter begin, Iter end, const Comparator & comp = {})
157{
158 return strictlyDecreasingPrefix(begin, end, std::not_fn(comp));
159}
160
165template<std::bidirectional_iterator Iter, typename Comparator = std::less<std::iter_value_t<Iter>>>
166Iter weaklyIncreasingSuffix(Iter begin, Iter end, const Comparator & comp = {})
167{
168 return strictlyDecreasingSuffix(begin, end, std::not_fn(comp));
169}
170
210template<std::random_access_iterator Iter, typename Comparator = std::less<std::iter_value_t<Iter>>>
211/* ValueType must be default constructible to create the temporary buffer */
212 requires std::is_default_constructible_v<std::iter_value_t<Iter>>
213void peeksort(Iter begin, Iter end, Comparator comp = {})
214{
215 auto length = std::distance(begin, end);
216
217 /* Special-case very simple inputs. This is identical to how libc++ does it. */
218 switch (length) {
219 case 0:
220 [[fallthrough]];
221 case 1:
222 return;
223 case 2:
224 if (comp(*--end, *begin)) /* [a, b], b < a */
225 std::swap(*begin, *end);
226 return;
227 }
228
229 using ValueType = std::iter_value_t<Iter>;
230 auto workingBuffer = std::vector<ValueType>(length);
231
232 /*
233 * sorts [begin, end), assuming that [begin, leftRunEnd) and
234 * [rightRunBegin, end) are sorted.
235 * Modified implementation from:
236 * https://github.com/sebawild/powersort/blob/1d078b6be9023e134c4f8f6de88e2406dc681e89/src/sorts/peeksort.h
237 */
238 auto peeksortImpl = [&workingBuffer,
239 &comp](auto & peeksortImpl, Iter begin, Iter end, Iter leftRunEnd, Iter rightRunBegin) {
240 if (leftRunEnd == end || rightRunBegin == begin)
241 return;
242
243 /* Dispatch to simpler insertion sort implementation for smaller cases
244 Cut-off limit is the same as in libstdc++
245 https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4977
246 */
247 static constexpr std::size_t insertionsortThreshold = 16;
248 size_t length = std::distance(begin, end);
249 if (length <= insertionsortThreshold)
250 return insertionsort(begin, end, comp);
251
252 Iter middle = std::next(begin, (length / 2)); /* Middle split between m and m - 1 */
253
254 if (middle <= leftRunEnd) {
255 /* |XXXXXXXX|XX X| */
256 peeksortImpl(peeksortImpl, leftRunEnd, end, std::next(leftRunEnd), rightRunBegin);
257 mergeSortedRunsInPlace(begin, leftRunEnd, end, workingBuffer.begin(), comp);
258 return;
259 } else if (middle >= rightRunBegin) {
260 /* |XX X|XXXXXXXX| */
261 peeksortImpl(peeksortImpl, begin, rightRunBegin, leftRunEnd, std::prev(rightRunBegin));
262 mergeSortedRunsInPlace(begin, rightRunBegin, end, workingBuffer.begin(), comp);
263 return;
264 }
265
266 /* Find middle run, i.e., run containing m - 1 */
267 Iter i, j;
268
269 if (!comp(*middle, *std::prev(middle)) /* *std::prev(middle) <= *middle */) {
270 i = weaklyIncreasingSuffix(leftRunEnd, middle, comp);
271 j = weaklyIncreasingPrefix(std::prev(middle), rightRunBegin, comp);
272 } else {
273 i = strictlyDecreasingSuffix(leftRunEnd, middle, comp);
274 j = strictlyDecreasingPrefix(std::prev(middle), rightRunBegin, comp);
275 std::reverse(i, j);
276 }
277
278 if (i == begin && j == end)
279 return; /* single run */
280
281 if (middle - i < j - middle) {
282 /* |XX x|xxxx X| */
283 peeksortImpl(peeksortImpl, begin, i, leftRunEnd, std::prev(i));
284 peeksortImpl(peeksortImpl, i, end, j, rightRunBegin);
285 mergeSortedRunsInPlace(begin, i, end, workingBuffer.begin(), comp);
286 } else {
287 /* |XX xxx|x X| */
288 peeksortImpl(peeksortImpl, begin, j, leftRunEnd, i);
289 peeksortImpl(peeksortImpl, j, end, std::next(j), rightRunBegin);
290 mergeSortedRunsInPlace(begin, j, end, workingBuffer.begin(), comp);
291 }
292 };
293
294 peeksortImpl(peeksortImpl, begin, end, /*leftRunEnd=*/begin, /*rightRunBegin=*/end);
295}
296
297} // namespace nix
Iter weaklyIncreasingPrefix(Iter begin, Iter end, const Comparator &comp={})
Definition sort.hh:156
void mergeSortedRunsInPlace(Iter begin, Iter middle, Iter end, BufIter workingBegin, Comparator comp={})
Definition sort.hh:68
Iter strictlyDecreasingSuffix(Iter begin, Iter end, const Comparator &comp={})
Definition sort.hh:141
void insertionsort(Iter begin, Iter end, Comparator comp={})
Definition sort.hh:108
Iter strictlyDecreasingPrefix(Iter begin, Iter end, const Comparator &comp={})
Definition sort.hh:126
Iter weaklyIncreasingSuffix(Iter begin, Iter end, const Comparator &comp={})
Definition sort.hh:166
void peeksort(Iter begin, Iter end, Comparator comp={})
Definition sort.hh:213
ValueType
Definition value.hh:77