2 This module provides a $(D BinaryHeap) (aka priority queue)
3 adaptor that makes a binary heap out of any user-provided random-access range.
5 This module is a submodule of $(MREF std, container).
7 Source: $(PHOBOSSRC std/container/_binaryheap.d)
9 Copyright: 2010- Andrei Alexandrescu. All rights reserved by the respective holders.
11 License: Distributed under the Boost Software License, Version 1.0.
12 (See accompanying file LICENSE_1_0.txt or copy at $(HTTP
13 boost.org/LICENSE_1_0.txt)).
15 Authors: $(HTTP erdani.com, Andrei Alexandrescu)
17 module std.container.binaryheap;
19 import std.range.primitives;
22 public import std.container.util;
27 import std.algorithm.comparison : equal;
28 import std.range : take;
29 auto maxHeap = heapify([4, 7, 3, 1, 5]);
30 assert(maxHeap.take(3).equal([7, 5, 4]));
32 auto minHeap = heapify!"a > b"([4, 7, 3, 1, 5]);
33 assert(minHeap.take(3).equal([1, 3, 4]));
38 Implements a $(HTTP en.wikipedia.org/wiki/Binary_heap, binary heap)
39 container on top of a given random-access range type (usually $(D
40 T[])) or a random-access container type (usually $(D Array!T)). The
41 documentation of $(D BinaryHeap) will refer to the underlying range or
42 container as the $(I store) of the heap.
44 The binary heap induces structure over the underlying store such that
45 accessing the largest element (by using the $(D front) property) is a
46 $(BIGOH 1) operation and extracting it (by using the $(D
47 removeFront()) method) is done fast in $(BIGOH log n) time.
49 If $(D less) is the less-than operator, which is the default option,
50 then $(D BinaryHeap) defines a so-called max-heap that optimizes
51 extraction of the $(I largest) elements. To define a min-heap,
52 instantiate BinaryHeap with $(D "a > b") as its predicate.
54 Simply extracting elements from a $(D BinaryHeap) container is
55 tantamount to lazily fetching elements of $(D Store) in descending
56 order. Extracting elements from the $(D BinaryHeap) to completion
57 leaves the underlying store sorted in ascending order but, again,
58 yields elements in descending order.
60 If $(D Store) is a range, the $(D BinaryHeap) cannot grow beyond the
61 size of that range. If $(D Store) is a container that supports $(D
62 insertBack), the $(D BinaryHeap) may grow by adding elements to the
65 struct BinaryHeap(Store, alias less = "a < b")
66 if (isRandomAccessRange!(Store) || isRandomAccessRange!(typeof(Store.init[])))
68 import std.algorithm.comparison : min;
69 import std.algorithm.mutation : move, swapAt;
70 import std.algorithm.sorting : HeapOps;
71 import std.exception : enforce;
72 import std.functional : binaryFun;
73 import std.typecons : RefCounted, RefCountedAutoInitialize;
75 static if (isRandomAccessRange!Store)
78 alias Range = typeof(Store.init[]);
79 alias percolate = HeapOps!(less, Range).percolate;
80 alias buildHeap = HeapOps!(less, Range).buildHeap;
82 // Really weird @@BUG@@: if you comment out the "private:" label below,
83 // std.algorithm can't unittest anymore
86 // The payload includes the support store and the effective length
87 private static struct Data
92 private RefCounted!(Data, RefCountedAutoInitialize.no) _payload;
93 // Comparison predicate
94 private alias comp = binaryFun!(less);
95 // Convenience accessors
96 private @property ref Store _store()
98 assert(_payload.refCountedStore.isInitialized);
99 return _payload._store;
101 private @property ref size_t _length()
103 assert(_payload.refCountedStore.isInitialized);
104 return _payload._length;
107 // Asserts that the heap property is respected.
108 private void assertValid()
112 import std.conv : to;
113 if (!_payload.refCountedStore.isInitialized) return;
114 if (_length < 2) return;
115 for (size_t n = _length - 1; n >= 1; --n)
117 auto parentIdx = (n - 1) / 2;
118 assert(!comp(_store[parentIdx], _store[n]), to!string(n));
123 // @@@BUG@@@: add private here, std.algorithm doesn't unittest anymore
124 /*private*/ void pop(Store store)
126 assert(!store.empty, "Cannot pop an empty store.");
127 if (store.length == 1) return;
128 auto t1 = store[].moveFront();
129 auto t2 = store[].moveBack();
130 store.front = move(t2);
131 store.back = move(t1);
132 percolate(store[], 0, store.length - 1);
138 Converts the store $(D s) into a heap. If $(D initialSize) is
139 specified, only the first $(D initialSize) elements in $(D s)
140 are transformed into a heap, after which the heap can grow up
141 to $(D r.length) (if $(D Store) is a range) or indefinitely (if
142 $(D Store) is a container with $(D insertBack)). Performs
143 $(BIGOH min(r.length, initialSize)) evaluations of $(D less).
145 this(Store s, size_t initialSize = size_t.max)
147 acquire(s, initialSize);
151 Takes ownership of a store. After this, manipulating $(D s) may make
152 the heap work incorrectly.
154 void acquire(Store s, size_t initialSize = size_t.max)
156 _payload.refCountedStore.ensureInitialized();
158 _length = min(_store.length, initialSize);
159 if (_length < 2) return;
165 Takes ownership of a store assuming it already was organized as a
168 void assume(Store s, size_t initialSize = size_t.max)
170 _payload.refCountedStore.ensureInitialized();
172 _length = min(_store.length, initialSize);
177 Clears the heap. Returns the portion of the store from $(D 0) up to
178 $(D length), which satisfies the $(LINK2 https://en.wikipedia.org/wiki/Heap_(data_structure),
183 if (!_payload.refCountedStore.isInitialized)
185 return typeof(_store[0 .. _length]).init;
188 auto result = _store[0 .. _length];
189 _payload = _payload.init;
194 Returns $(D true) if the heap is _empty, $(D false) otherwise.
196 @property bool empty()
202 Returns a duplicate of the heap. The $(D dup) method is available only if the
203 underlying store supports it.
205 static if (is(typeof((Store s) { return s.dup; }(Store.init)) == Store))
207 @property BinaryHeap dup()
210 if (!_payload.refCountedStore.isInitialized) return result;
211 result.assume(_store.dup, length);
217 Returns the _length of the heap.
219 @property size_t length()
221 return _payload.refCountedStore.isInitialized ? _length : 0;
225 Returns the _capacity of the heap, which is the length of the
226 underlying store (if the store is a range) or the _capacity of the
227 underlying store (if the store is a container).
229 @property size_t capacity()
231 if (!_payload.refCountedStore.isInitialized) return 0;
232 static if (is(typeof(_store.capacity) : size_t))
234 return _store.capacity;
238 return _store.length;
243 Returns a copy of the _front of the heap, which is the largest element
244 according to $(D less).
246 @property ElementType!Store front()
248 enforce(!empty, "Cannot call front on an empty heap.");
253 Clears the heap by detaching it from the underlying store.
257 _payload = _payload.init;
261 Inserts $(D value) into the store. If the underlying store is a range
262 and $(D length == capacity), throws an exception.
264 size_t insert(ElementType!Store value)
266 static if (is(typeof(_store.insertBack(value))))
268 _payload.refCountedStore.ensureInitialized();
269 if (length == _store.length)
272 _store.insertBack(value);
277 _store[_length] = value;
282 import std.traits : isDynamicArray;
283 static if (isDynamicArray!Store)
285 if (length == _store.length)
286 _store.length = (length < 6 ? 8 : length * 3 / 2);
287 _store[_length] = value;
292 enforce(length < _store.length,
293 "Cannot grow a heap created over a range");
297 // sink down the element
298 for (size_t n = _length; n; )
300 auto parentIdx = (n - 1) / 2;
301 if (!comp(_store[parentIdx], _store[n])) break; // done!
302 // must swap and continue
303 _store.swapAt(parentIdx, n);
307 debug(BinaryHeap) assertValid();
312 Removes the largest element from the heap.
316 enforce(!empty, "Cannot call removeFront on an empty heap.");
319 auto t1 = _store[].moveFront();
320 auto t2 = _store[].moveAt(_length - 1);
321 _store.front = move(t2);
322 _store[_length - 1] = move(t1);
325 percolate(_store[], 0, _length);
329 alias popFront = removeFront;
332 Removes the largest element from the heap and returns a copy of
333 it. The element still resides in the heap's store. For performance
334 reasons you may want to use $(D removeFront) with heaps of objects
335 that are expensive to copy.
337 ElementType!Store removeAny()
340 return _store[_length];
344 Replaces the largest element in the store with $(D value).
346 void replaceFront(ElementType!Store value)
348 // must replace the top
349 assert(!empty, "Cannot call replaceFront on an empty heap.");
350 _store.front = value;
351 percolate(_store[], 0, _length);
352 debug(BinaryHeap) assertValid();
356 If the heap has room to grow, inserts $(D value) into the store and
357 returns $(D true). Otherwise, if $(D less(value, front)), calls $(D
358 replaceFront(value)) and returns again $(D true). Otherwise, leaves
359 the heap unaffected and returns $(D false). This method is useful in
360 scenarios where the smallest $(D k) elements of a set of candidates
363 bool conditionalInsert(ElementType!Store value)
365 _payload.refCountedStore.ensureInitialized();
366 if (_length < _store.length)
372 assert(!_store.empty, "Cannot replace front of an empty heap.");
373 if (!comp(value, _store.front)) return false; // value >= largest
374 _store.front = value;
376 percolate(_store[], 0, _length);
377 debug(BinaryHeap) assertValid();
382 Swapping is allowed if the heap is full. If $(D less(value, front)), the
383 method exchanges store.front and value and returns $(D true). Otherwise, it
384 leaves the heap unaffected and returns $(D false).
386 bool conditionalSwap(ref ElementType!Store value)
388 _payload.refCountedStore.ensureInitialized();
389 assert(_length == _store.length);
390 assert(!_store.empty, "Cannot swap front of an empty heap.");
392 if (!comp(value, _store.front)) return false; // value >= largest
394 import std.algorithm.mutation : swap;
395 swap(_store.front, value);
397 percolate(_store[], 0, _length);
398 debug(BinaryHeap) assertValid();
404 /// Example from "Introduction to Algorithms" Cormen et al, p 146
407 import std.algorithm.comparison : equal;
408 int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
411 assert(h.front == 16);
412 // a has the heap property
413 assert(equal(a, [ 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 ]));
416 /// $(D BinaryHeap) implements the standard input range interface, allowing
417 /// lazy iteration of the underlying range in descending order.
420 import std.algorithm.comparison : equal;
421 import std.range : take;
422 int[] a = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7];
423 auto top5 = heapify(a).take(5);
424 assert(top5.equal([16, 14, 10, 9, 8]));
428 Convenience function that returns a $(D BinaryHeap!Store) object
429 initialized with $(D s) and $(D initialSize).
431 BinaryHeap!(Store, less) heapify(alias less = "a < b", Store)(Store s,
432 size_t initialSize = size_t.max)
435 return BinaryHeap!(Store, less)(s, initialSize);
441 import std.conv : to;
442 import std.range.primitives;
444 // example from "Introduction to Algorithms" Cormen et al., p 146
445 int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
447 h = heapify!"a < b"(a);
448 assert(h.front == 16);
449 assert(a == [ 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 ]);
450 auto witness = [ 16, 14, 10, 9, 8, 7, 4, 3, 2, 1 ];
451 for (; !h.empty; h.removeFront(), witness.popFront())
453 assert(!witness.empty);
454 assert(witness.front == h.front);
456 assert(witness.empty);
459 int[] a = [ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ];
460 int[] b = new int[a.length];
461 BinaryHeap!(int[]) h = BinaryHeap!(int[])(b, 0);
466 assert(b == [ 16, 14, 10, 8, 7, 3, 9, 1, 4, 2 ], to!string(b));
472 // Test range interface.
473 import std.algorithm.comparison : equal;
474 int[] a = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7];
476 static assert(isInputRange!(typeof(h)));
477 assert(h.equal([16, 14, 10, 9, 8, 7, 4, 3, 2, 1]));
480 @system unittest // 15675
482 import std.container.array : Array;
484 Array!int elements = [1, 2, 10, 12];
485 auto heap = heapify(elements);
486 assert(heap.front == 12);
489 @system unittest // 16072
491 auto q = heapify!"a > b"([2, 4, 5]);
494 assert(q.front == 1);
496 // test more multiple grows
498 auto r = heapify!"a < b"(arr);
499 foreach (i; 0 .. 100)
502 assert(r.front == 99);
507 import std.algorithm.comparison : equal;
508 int[] a = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7];
509 auto heap = heapify(a);
510 auto dup = heap.dup();
511 assert(dup.equal([16, 14, 10, 9, 8, 7, 4, 3, 2, 1]));
516 static struct StructWithoutDup
519 @disable StructWithoutDup dup()
527 // Assert Binary heap can be created when Store doesn't have dup
528 // if dup is not used.
529 assert(__traits(compiles, ()
531 auto s = StructWithoutDup([1,2]);
535 // Assert dup can't be used on BinaryHeaps when Store doesn't have dup
536 assert(!__traits(compiles, ()
538 auto s = StructWithoutDup([1,2]);
546 static struct StructWithDup
557 // Assert dup can be used on BinaryHeaps when Store has dup
558 assert(__traits(compiles, ()
560 auto s = StructWithDup([1, 2]);
568 import std.algorithm.comparison : equal;
569 import std.internal.test.dummyrange;
571 alias RefRange = DummyRange!(ReturnBy.Reference, Length.Yes, RangeType.Random);
578 auto heap = heapify(a);
579 foreach (ref elem; b)
581 heap.conditionalSwap(elem);
584 assert(equal(heap, [ 5, 5, 4, 4, 3, 3, 2, 2, 1, 1]));
585 assert(equal(b, [10, 9, 8, 7, 6, 6, 7, 8, 9, 10]));
588 @system unittest // Issue 17314
590 import std.algorithm.comparison : equal;
592 auto heap = heapify(a);
594 assert(equal(heap, [6, 5]));