Online median finding and maintainence

Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.

Thoughts:
We maintain two heaps: minHeap and maxHeap. If we represent these two heaps in terms of list, minHeap is in descending order whereas maxHeap is in ascending order. If we manage to maintain these two heaps while getting new numbers, the median is either in the first place of minHeap or in the first place of maxHeap (or the average of these two). Consider the example of sequence of numbers: 1, 2, 3, 4 and 5. The maintainence of minHeap, maxHeap are shown below:
After 1 coming:
minHeap: 1
maxHeap:
median : 1

After 2 coming:
minHeap: 1
maxHeap: 2
median : 1.5

After 3 coming:
minHeap: 1
maxHeap: 2 3
median : 2

After 4 coming:
minHeap: 1 2
maxHeap: 3 4
median : 2.5

After 5 coming:
minHeap: 1 2
maxHeap: 3 4 5
median : 3

Codes:

	public static class maxComparator implements Comparator<Double> {
		public int compare(Double o1, Double o2) {
			return -o1.compareTo(o2);
		}
	}

	static PriorityQueue<Double> minHeap = new PriorityQueue<Double>(11,
			new maxComparator());
	static PriorityQueue<Double> maxHeap = new PriorityQueue<Double>();

	public static void addToHeap(double number) {
		if (minHeap.size() == maxHeap.size()) {
			if (minHeap.isEmpty())
				minHeap.add(number);
			else if (number > minHeap.peek())
				maxHeap.add(number);
			else { // number < minHeap.peek()
				maxHeap.add(minHeap.poll());
				minHeap.add(number);
			}
		} else if (minHeap.size() > maxHeap.size()) {
			if (number > minHeap.peek())
				maxHeap.add(number);
			else { // number <= minHeap.peek()
				maxHeap.add(minHeap.poll());
				minHeap.add(number);
			}
		} else { // minHeap.size() < maxHeap.size()
			if (number < maxHeap.peek())
				minHeap.add(number);
			else { // number >= maxHeap.peek()
				minHeap.add(maxHeap.poll());
				maxHeap.add(number);
			}
		}
	}

	public static double getMedian() {
		if (minHeap.size() == maxHeap.size())
			return (minHeap.peek() + maxHeap.peek()) / 2;
		else if (minHeap.size() > maxHeap.size())
			return minHeap.peek();
		else
			return maxHeap.peek();
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: