Commit b4d4edaa authored by Lars Buitinck's avatar Lars Buitinck

add support for C++ stdlib heap operations

parent 2b3e048e
......@@ -47,6 +47,8 @@ Features added
* Defines dynamic_cast et al. in `libcpp.cast`.
* Support for C++ heap data structure operations (from ``<algorithm>``).
Optimizations
-------------
......
cdef extern from "<algorithm>" namespace "std" nogil:
void make_heap[Iter](Iter first, Iter last)
void make_heap[Iter, Compare](Iter first, Iter last, Compare comp)
void pop_heap[Iter](Iter first, Iter last)
void pop_heap[Iter, Compare](Iter first, Iter last, Compare comp)
void push_heap[Iter](Iter first, Iter last)
void push_heap[Iter, Compare](Iter first, Iter last, Compare comp)
void sort_heap[Iter](Iter first, Iter last)
void sort_heap[Iter, Compare](Iter first, Iter last, Compare comp)
# tag: cpp
from libcpp cimport bool
from libcpp.algorithm cimport make_heap, sort_heap
from libcpp.vector cimport vector
# XXX should use std::greater, but I don't know how to wrap that.
cdef inline bool greater(int x, int y):
return x > y
def heapsort(l, bool reverse=False):
"""
>>> heapsort([3, 5, 1, 0, 2, 4])
[0, 1, 2, 3, 4, 5]
>>> heapsort([3, 5, 1, 0, 2, 4], reverse=True)
[5, 4, 3, 2, 1, 0]
"""
cdef vector[int] v = l
if reverse:
make_heap(v.begin(), v.end(), greater)
sort_heap(v.begin(), v.end(), greater)
else:
make_heap(v.begin(), v.end())
sort_heap(v.begin(), v.end())
return v
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment