blob: 3b2f5394beabf1570c62e46503b243dffe659e71 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
tome3489412014-08-29 02:30:38 -070016package org.onlab.graph;
17
18import com.google.common.collect.ImmutableList;
19
20import java.util.Comparator;
21import java.util.Iterator;
22import java.util.List;
23import java.util.Objects;
24
tomeadbb462014-09-07 16:10:19 -070025import static com.google.common.base.MoreObjects.toStringHelper;
tome3489412014-08-29 02:30:38 -070026import static com.google.common.base.Preconditions.checkNotNull;
27
28/**
29 * Implementation of an array-backed heap structure whose sense of order is
30 * imposed by the provided comparator.
31 * <p/>
32 * While this provides similar functionality to {@link java.util.PriorityQueue}
33 * data structure, one key difference is that external entities can control
34 * when to restore the heap property, which is done through invocation of the
35 * {@link #heapify} method.
36 * <p/>
37 * This class is not thread-safe and care must be taken to prevent concurrent
38 * modifications.
39 *
40 * @param <T> type of the items on the heap
41 */
42public class Heap<T> {
43
tome3489412014-08-29 02:30:38 -070044 private final List<T> data;
45 private final Comparator<T> comparator;
46
47 /**
48 * Creates a new heap backed by the specified list. In the interest of
49 * efficiency, the list should be array-backed. Also, for the same reason,
50 * the data is not copied and therefore, the caller must assure that the
51 * backing data is not altered in any way.
52 *
53 * @param data backing data list
54 * @param comparator comparator for ordering the heap items
55 */
56 public Heap(List<T> data, Comparator<T> comparator) {
57 this.data = checkNotNull(data, "Data cannot be null");
58 this.comparator = checkNotNull(comparator, "Comparator cannot be null");
59 heapify();
60 }
61
62 /**
63 * Restores the heap property by re-arranging the elements in the backing
64 * array as necessary following any heap modifications.
65 */
66 public void heapify() {
67 for (int i = data.size() / 2; i >= 0; i--) {
68 heapify(i);
69 }
70 }
71
72 /**
73 * Returns the current size of the heap.
74 *
75 * @return number of items in the heap
76 */
77 public int size() {
78 return data.size();
79 }
80
81 /**
82 * Returns true if there are no items in the heap.
83 *
84 * @return true if heap is empty
85 */
86 public boolean isEmpty() {
87 return data.isEmpty();
88 }
89
90 /**
91 * Returns the most extreme item in the heap.
92 *
93 * @return heap extreme or null if the heap is empty
94 */
95 public T extreme() {
96 return data.isEmpty() ? null : data.get(0);
97 }
98
99 /**
100 * Extracts and returns the most extreme item from the heap.
101 *
102 * @return heap extreme or null if the heap is empty
103 */
104 public T extractExtreme() {
105 if (!isEmpty()) {
106 T extreme = extreme();
107
108 data.set(0, data.get(data.size() - 1));
109 data.remove(data.size() - 1);
110 heapify();
111 return extreme;
112 }
113 return null;
114 }
115
116 /**
117 * Inserts the specified item into the heap and returns the modified heap.
118 *
119 * @param item item to be inserted
120 * @return the heap self
121 * @throws IllegalArgumentException if the heap is already full
122 */
123 public Heap<T> insert(T item) {
124 data.add(item);
125 bubbleUp();
126 return this;
127 }
128
129 /**
130 * Returns iterator to traverse the heap level-by-level. This iterator
131 * does not permit removal of items.
132 *
133 * @return non-destructive heap iterator
134 */
135 public Iterator<T> iterator() {
136 return ImmutableList.copyOf(data).iterator();
137 }
138
139 // Bubbles up the last item in the heap to its proper position to restore
140 // the heap property.
141 private void bubbleUp() {
142 int child = data.size() - 1;
143 while (child > 0) {
144 int parent = child / 2;
145 if (comparator.compare(data.get(child), data.get(parent)) < 0) {
146 break;
147 }
148 swap(child, parent);
149 child = parent;
150 }
151 }
152
153 // Restores the heap property of the specified heap layer.
154 private void heapify(int i) {
155 int left = 2 * i + 1;
156 int right = 2 * i;
157 int extreme = i;
158
159 if (left < data.size() &&
160 comparator.compare(data.get(extreme), data.get(left)) < 0) {
161 extreme = left;
162 }
163
164 if (right < data.size() &&
165 comparator.compare(data.get(extreme), data.get(right)) < 0) {
166 extreme = right;
167 }
168
169 if (extreme != i) {
170 swap(i, extreme);
171 heapify(extreme);
172 }
173 }
174
175 // Swaps two heap items identified by their respective indexes.
176 private void swap(int i, int k) {
177 T aux = data.get(i);
178 data.set(i, data.get(k));
179 data.set(k, aux);
180 }
181
182 @Override
183 public boolean equals(Object obj) {
tomfc9a4ff2014-09-22 18:22:47 -0700184 if (this == obj) {
185 return true;
186 }
tome3489412014-08-29 02:30:38 -0700187 if (obj instanceof Heap) {
188 Heap that = (Heap) obj;
189 return this.getClass() == that.getClass() &&
190 Objects.equals(this.comparator, that.comparator) &&
191 Objects.deepEquals(this.data, that.data);
192 }
193 return false;
194 }
195
196 @Override
197 public int hashCode() {
198 return Objects.hash(comparator, data);
199 }
200
201 @Override
202 public String toString() {
tomeadbb462014-09-07 16:10:19 -0700203 return toStringHelper(this)
tome3489412014-08-29 02:30:38 -0700204 .add("data", data)
205 .add("comparator", comparator)
206 .toString();
207 }
208
209}