Created
March 15, 2015 02:33
-
-
Save jonniesweb/3d533990c4a7612501ab to your computer and use it in GitHub Desktop.
A quick and dirty fixed buffer to determine medians of a set of numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A fixed buffer that determines the median of its values. Very inefficient for | |
* high buffer lengths. | |
* | |
* Here you go Matt! | |
*/ | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Deque; | |
import java.util.LinkedList; | |
public class FixedBuffer { | |
private Deque<Integer> list; | |
private int maxSize; | |
public FixedBuffer(int maxSize) { | |
this.maxSize = maxSize; | |
list = new LinkedList<>(); | |
} | |
public void put(int i) { | |
if (list.size() >= maxSize) { | |
list.pop(); | |
} | |
list.add(i); | |
} | |
public int getMedian() { | |
ArrayList<Integer> sortedList = new ArrayList<>(list); | |
Collections.sort(sortedList); | |
return sortedList.get(sortedList.size() / 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment