All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bhu.nlp.utils.MaxHeap Maven / Gradle / Ivy

There is a newer version: 1.0.3
Show newest version
package org.bhu.nlp.utils;

import java.util.*;


public class MaxHeap {

	private PriorityQueue queue;

	private int maxSize;

	public MaxHeap(int maxSize, Comparator comparator) {
		if (maxSize <= 0)
			throw new IllegalArgumentException();
		this.maxSize = maxSize;
		this.queue = new PriorityQueue(maxSize, comparator);
	}

	public boolean add(E e) {
		if (queue.size() < maxSize) {
			queue.add(e);
			return true;
		} else {
			E peek = queue.peek();
			if (queue.comparator().compare(e, peek) > 0) {
				queue.poll();
				queue.add(e);
				return true;
			}
		}
		return false;
	}

	public MaxHeap addAll(Collection collection) {
		for (E e : collection) {
			add(e);
		}

		return this;
	}

	public List toList() {
		ArrayList list = new ArrayList(queue.size());
		while (!queue.isEmpty()) {
			list.add(0, queue.poll());
		}

		return list;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy