I made a median filter algorithm and I want to optimize it. Currently it's taking around 1 second to filter 2MM lines(a file read into an ArrayList elements) and I am trying to reduce it to less(maybe half the time?) I'm using ArrayLists for my algorithm and minimized the use of nested loops as well to avoid an increase in time, however I still can't achieve lower than 0.98 seconds tops.
Here's a code snippet that does the median filter:
//Start Filter Algorithm 2
int index=0;
while(index<filterSize){
tempElements.add(this.elements.get(index+counter)); //Add element to a temporary arraylist
index+=1;
if(index==filterSize){
outputElements.add(tempElements.get((filterSize-1)/2)); //Add median Value to output ArrayList
tempElements.clear(); //Clear temporary ArrayList
index = 0; //Reset index
counter+=1; //Counter increments by 1 to move to start on next element in elements ArrayList
}
if(elementsSize-counter <filterSize){
break; //Break if there is not enough elements for the filtering to work
}
}
What's happening is that I'm looping through the elements arraylist for the filterSize I provided. Then I add the elements to a temporary(tempElements) arraylist, sort it using Collections.sort()(this is what I want to avoid), find the median value and add it to my final output arraylist. Then I clear the tempElements arraylist and keep going through my loop until I cannot filter anymore due to the lack of elements(less than filterSize).
I'm just looking for a way to optimize it and get it faster. I tried to use a TreeSet but I cannot get the value at an index from it.
Thanks