Median Of Running Array Algorithm

The Median of Running Array Algorithm is a technique that computes the median of an ever-changing dataset in real-time. This algorithm is particularly useful in situations where the dataset is constantly being updated or modified, such as in streaming applications or online data processing systems. The median, as a measure of central tendency, provides a more reliable representation of the dataset than the mean, as it is less sensitive to extreme values and outliers. By continuously updating the median as new data points arrive or old ones are removed, the algorithm allows for real-time analysis and decision-making based on the current state of the dataset. The main idea behind the Median of Running Array Algorithm is to maintain two heaps - a max-heap for the lower half of the dataset, and a min-heap for the upper half. As new data points are added, they are inserted into either the max-heap or the min-heap, depending on whether they are smaller or larger than the current median, respectively. The heaps are then balanced to ensure that they have roughly equal sizes, which allows the median to be easily calculated as either the maximum element of the max-heap, the minimum element of the min-heap, or the average of the two, depending on the size of the heaps. This balancing process ensures that the algorithm can efficiently compute the median in logarithmic time complexity, making it suitable for processing large datasets or high-speed data streams.
package Misc;

import java.util.Collections;
import java.util.PriorityQueue;


/**
 * @author shrutisheoran
 */
public class MedianOfRunningArray {
    private PriorityQueue<Integer> p1;
    private PriorityQueue<Integer> p2;

    //Constructor
    public MedianOfRunningArray() {
        this.p1 = new PriorityQueue<>(Collections.reverseOrder()); //Max Heap
        this.p2 = new PriorityQueue<>(); //Min Heap
    }

    /* 
        Inserting lower half of array to max Heap
        and upper half to min heap
    */
    public void insert(Integer e) {
        p2.add(e);
        if (p2.size() - p1.size() > 1)
            p1.add(p2.remove());
    }

    /*
        Returns median at any given point
    */
    public Integer median() {
        if (p1.size() == p2.size())
            return (p1.peek() + p2.peek()) / 2;
        return p1.size() > p2.size() ? p1.peek() : p2.peek();
    }

    public static void main(String[] args) {
        /*
            Testing the median function
        */

        MedianOfRunningArray p = new MedianOfRunningArray();
        int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14};
        for (int i = 0; i < 9; i++) {
            p.insert(arr[i]);
            System.out.print(p.median() + " ");
        }
    }

}

LANGUAGE:

DARK MODE: