堆结构的java实现
闲时写了一个heap的数据结构,支持最大堆,最小堆。
通过Comparator控制堆的性质(是最大堆还是最小堆)
创建最大堆private void heapify(int i, int size) { int l = left(i); int r = right(i); int next = i; if (l < size && c.compare(heap[l], heap[i]) > 0) next = l; if (r < size && c.compare(heap[r], heap[next]) > 0) next = r; if (i == next) return; swap(i, next); heapify(next, size); }
有点问题,
swap(i, next);
heapify(next, size);
应该放到if块里吧? 2 楼 attend 2012-01-13 不好意思,看错了。 if (r < size && c.compare(heap[r], heap[next]) > 0) 看成
if (r < size && c.compare(heap[r], heap[i]) > 0) 了。