1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// UNSUPPORTED: c++03, c++11
10
11// <algorithm>
12
13// template<class Iter>
14// void sort_heap(Iter first, Iter last);
15
16#include <algorithm>
17#include <cassert>
18#include <random>
19
20#include "test_macros.h"
21
22struct Stats {
23 int compared = 0;
24 int copied = 0;
25 int moved = 0;
26} stats;
27
28struct MyInt {
29 int value;
30 explicit MyInt(int xval) : value(xval) {}
31 MyInt(const MyInt& other) : value(other.value) { ++stats.copied; }
32 MyInt(MyInt&& other) : value(other.value) { ++stats.moved; }
33 MyInt& operator=(const MyInt& other) {
34 value = other.value;
35 ++stats.copied;
36 return *this;
37 }
38 MyInt& operator=(MyInt&& other) {
39 value = other.value;
40 ++stats.moved;
41 return *this;
42 }
43 friend bool operator<(const MyInt& a, const MyInt& b) {
44 ++stats.compared;
45 return a.value < b.value;
46 }
47};
48
49int main(int, char**) {
50 constexpr int N = (1 << 20);
51 std::vector<MyInt> v;
52 v.reserve(n: N);
53 std::mt19937 g;
54 for (int i = 0; i < N; ++i) {
55 v.emplace_back(args&: i);
56 }
57 for (int logn = 10; logn <= 20; ++logn) {
58 const int n = (1 << logn);
59 auto first = v.begin();
60 auto last = v.begin() + n;
61 const int debug_elements = std::min(a: 100, b: n);
62 // Multiplier 2 because of comp(a,b) comp(b, a) checks.
63 const int debug_comparisons = 2 * (debug_elements + 1) * debug_elements;
64 (void)debug_comparisons;
65 std::shuffle(first: first, last: last, g&: g);
66 std::make_heap(first: first, last: last);
67 // The exact stats of our current implementation are recorded here.
68 stats = {};
69 std::sort_heap(first: first, last: last);
70 LIBCPP_ASSERT(stats.copied == 0);
71 LIBCPP_ASSERT(stats.moved <= 2 * n + n * logn);
72#if _LIBCPP_HARDENING_MODE != _LIBCPP_HARDENING_MODE_DEBUG
73 LIBCPP_ASSERT(stats.compared <= n * logn);
74#else
75 LIBCPP_ASSERT(stats.compared <= 2 * n * logn + debug_comparisons);
76#endif
77 LIBCPP_ASSERT(std::is_sorted(first: first, last: last));
78 }
79 return 0;
80}
81

source code of libcxx/test/std/algorithms/alg.sorting/alg.heap.operations/sort.heap/complexity.pass.cpp