Skip to content

Instantly share code, notes, and snippets.

@jonniesweb
Created March 15, 2015 02:33
Show Gist options
  • Save jonniesweb/3d533990c4a7612501ab to your computer and use it in GitHub Desktop.
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
/**
* 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