After careful research and thought, I decided to post this question which is a "sequel" to my previous question asked earlier today.
I made an algorithm that finds the median of an ArrayList and bascially all I do is make a temporary ArrayList, then using Collections.sort() on that ArrayList, I can easily get the median. The problem with that is it takes too long for larger files and I am trying(without luck) to find an implementation of an algorithm to get the median of an unsorted Array(or ArrayList).
From what I read here, the Median of Medians algorithm is used followed by QuickSelect but I cannot find an actual implementation that is easy enough to understand.
Here's a snippet of my code that finds the median of an ArrayList of size filterSize
:
while(elements.size()-counter >= filterSize){
for(int i = 0; i<filterSize; i++){
tempElements.add(this.elements.get(i+counter));
if(i==filterSize){
break;
}
}
Collections.sort(tempElements); //Sort tempElements to find median
outputElements.add(tempElements.get((filterSize-1)/2)); //Add median to an output ArrayList after calculating median index
counter++;
tempElements.clear(); //Removes all elements from the tempElements and start again
}
Basically I'm trying to avoid the whole use of Collections.sort()
and tempElements.clear()
in the code, thus the reason to find a better algorithm for finding the median in linear time.
Thanks.