I've implemented a SortedList which takes in streams of floats and returns a median at any point.
public class SortedList {
float[] list;
int pos;
int capacity;
public SortedList(){
this.pos = 0;
this.capacity = 2;
list = new float[capacity];
}
public void offer(int item){
if(pos == 0){
list[pos] = item;
pos++;
return;
}
if(pos == 1){
if(item > list[0]){
list[1] = item;
}else{
float temp = list[0];
list[0] = item;
list[1] = temp;
}
pos++;
return;
}
if(pos - list.length <= 1) resize();
int index = -1;
for(int i=0; i< pos -1; i++){
if(item < list[i]){
index = i;
break;
}else if((item > list[i] && item < list[i+1])){
index = i+1;
break;
}
}
if(index > -1){
for(int i= pos; i > index; i--){
list[i] = list[i -1];
}
list[index] = item;
}else{
list[pos] = item;
}
pos++;
}
public float median(){
float median = -1;
if(pos%2 == 0){
median = (list[pos/2 -1] + list[(pos/2)])/2;
}else{
median = list[(pos/2)];
}
return median;
}
private void resize(){
capacity = capacity*2;
float[] arr = new float[capacity];
for(int i=0; i< pos; i++){
arr[i] = list[i];
}
list = arr;
}
public void trace(){
for(int i=0; i< pos; i++){
System.out.print(list[i] + " ");
}
System.out.println();
}
}
Invite comments on efficiency and accuracy. In the test case that I've used it works fine.