Skip to content

Commit 7e0ddb3

Browse files
committed
Add Median Of Running Array
1 parent 43e3366 commit 7e0ddb3

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Misc/MedianOfRunningArray.java

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.util.Collections;
2+
import java.util.PriorityQueue;
3+
4+
/**********************
5+
author: shrutisheoran
6+
***********************/
7+
8+
public class MedianOfRunningArray {
9+
private PriorityQueue<Integer> p1;
10+
private PriorityQueue<Integer> p2;
11+
12+
//Constructor
13+
public MedianOfRunningArray() {
14+
this.p1 = new PriorityQueue<>(Collections.reverseOrder()); //Max Heap
15+
this.p2 = new PriorityQueue<>(); //Min Heap
16+
}
17+
18+
/*
19+
Inserting lower half of array to max Heap
20+
and upper half to min heap
21+
*/
22+
public void insert(Integer e) {
23+
p2.add(e);
24+
if(p2.size() - p1.size() > 1)
25+
p1.add(p2.remove());
26+
}
27+
28+
/*
29+
Returns median at any given point
30+
*/
31+
public Integer median() {
32+
if(p1.size()==p2.size())
33+
return (p1.peek() + p2.peek())/2;
34+
return p1.size()>p2.size() ? p1.peek() : p2.peek();
35+
}
36+
37+
public static void main(String[] args) {
38+
/*
39+
Testing the median function
40+
*/
41+
42+
MedianOfRunningArray p = new MedianOfRunningArray();
43+
int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14};
44+
for(int i = 0 ; i < 9 ; i++) {
45+
p.insert(arr[i]);
46+
System.out.print(p.median() + " ");
47+
}
48+
}
49+
50+
}

0 commit comments

Comments
 (0)