From 88e63ddec23632956946536a6fe5132dc49051a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=99=93=E8=88=AA?= <1210603696@qq.com> Date: Tue, 14 Oct 2014 10:09:02 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90make=5Fheap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/Algorithm.h | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/TinySTL/Algorithm.h b/TinySTL/Algorithm.h index 412be08..b75d8d8 100644 --- a/TinySTL/Algorithm.h +++ b/TinySTL/Algorithm.h @@ -66,6 +66,70 @@ namespace TinySTL{ const T& max(const T& a, const T& b, Compare comp){ return (copm(a, b)) ? b : a; } + //********** [make_heap] *************** + template + static void up(RandomAccessIterator first, RandomAccessIterator last, Compare comp){//[first, last] + if (first != last){ + auto range = last - first + 1; + for (auto cur = last; rait > first; range /= 2){ + auto parent = first + (range / 2 - 1); + if (comp(*parent, *cur)) + TinySTL::swap(*parent, *cur); + cur = parent; + } + } + } + template + static void down(RandomAccessIterator first, RandomAccessIterator last, Compare comp){//[first, last] + if (first != last){ + decltype(last - first) range = 1; + for (auto cur = first; cur < last;range = cur - first + 1){ + auto child = first + (range * 2 - 1);//get the left child + if (child <= last){ + if ((child + 1) <= last && *(child + 1) > *child) + child = child + 1;//right child + if (comp(*cur, *child)) + TinySTL::swap(*cur, *child); + cur = child; + } + else + break; + } + } + } + template + void make_heap(RandomAccessIterator first, RandomAccessIterator last){ + TinySTL::make_heap(first, last, + typename TinySTL::less::value_type>()); + } + template + void make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp){ + const auto range = last - first; + for (auto rait = first + range - 1; rait > first; --rait){ + down(first, rait, comp); + } + } + //********* [push_heap] *************** + template + void push_heap(RandomAccessIterator first, RandomAccessIterator last); + template + void push_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); + //********* [pop_heap] *************** + template + void pop_heap(RandomAccessIterator first, RandomAccessIterator last); + template + void pop_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); + //********* [sort_heap] *************** + template + void sort_heap(RandomAccessIterator first, RandomAccessIterator last); + template + void sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); + //********* [is_heap] *************** + template + bool is_heap(RandomAccessIterator first, RandomAccessIterator last); + template + bool is_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp); } + #endif \ No newline at end of file