Planeshift
heap.h
Go to the documentation of this file.
1 /*
2  * heap.h
3  *
4  * Copyright (C) 2005 Atomic Blue (info@planeshift.it, http://www.planeshift.it)
5  *
6  * Credits : Andrew Dai
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation (version 2
11  * of the License).
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  *
20  * Creation Date: 10/Feb 2005
21  * Description : This is an implementation of a min heap. (a priority queue)
22  *
23  */
24 
25 #ifndef __HEAP_H__
26 #define __HEAP_H__
27 
28 #include <csutil/array.h>
29 
34 template <class T>
35 class Heap : protected csArray<T*>
36 {
37  // Work around gcc 3.4 braindamage.
38  using csArray<T*>::Get;
39  using csArray<T*>::Top;
40 
41 public:
42  Heap(int ilimit = 0)
43  : csArray<T*>(ilimit)
44  {
45  }
46 
47  size_t Length () const
48  {
49  return csArray<T*>::GetSize();
50  }
51 
52  void Insert(T* what)
53  {
54  size_t i;
55 
56  // Make room for new element
57  this->SetSize(Length() + 1);
58 
59  // This special case is required as we are not using a sentinel
60  if(Length() > 1)
61  for( i = Length()-1; i != 0 && *Get((i-1)/2) > *what; i = (i-1)/2)
62  this->Put(i, this->Get((i-1)/2));
63  else
64  i = 0;
65 
66  this->Put(i, what);
67  }
68 
69  T* DeleteMin()
70  {
71  size_t i, child;
72  T* minElement = this->Get(0);
73  T* lastElement = this->Top();
74 
75  CS_ASSERT(Length());
76  // Shrink the array by 1
77  this->Truncate(Length() - 1);
78 
79  if(!Length())
80  return minElement;
81 
82  for(i = 0; i * 2 + 1 < Length(); i = child)
83  {
84  // Find the smaller child
85  child = i * 2 + 1;
86  if( child != Length()-1 && *this->Get(child + 1) < *this->Get(child) )
87  child++;
88 
89  // Move it down one level
90  if( *lastElement > *this->Get(child))
91  this->Put(i, this->Get(child));
92  else
93  break;
94  }
95  this->Put(i, lastElement);
96  return minElement;
97  }
98 
99  T* FindMin()
100  {
101  if(Length())
102  return this->Get(0);
103  else
104  return NULL;
105  }
106 };
107 
110 #endif
111 
T * DeleteMin()
Definition: heap.h:69
void Insert(T *what)
Definition: heap.h:52
Definition: heap.h:35
T * FindMin()
Definition: heap.h:99
size_t Length() const
Definition: heap.h:47
Heap(int ilimit=0)
Definition: heap.h:42