Why do you insist on sorting the ADC readings? What problem is that trying to solve?

I'd get rid of the "bubble sort" and try starting with Richard's code.