I’m working on an algorithm that manipulates pictures.
Basically I will implement a diffusion (each pixel will get the median value of the 8 surrounding pixels + its own value).
what I will do is to create a array of 9 integers with the value, sort the array and get the median value at array[4].
I still don’t know what to use for the problem, what is the best sorting function to use for relatively small arrays? The sorting function will roughly be called x times, x being the number of pixels.
Heapsort seems a bit overkill. Quicksort will not perform that well. And I don’t want to implement really complex things.
What do you guys think?
If all you need is the median, there’s no need to do any sorting at all! (For long arrays, see http://en.wikipedia.org/wiki/Selection_algorithm for an O(n) algorithm; of course we’re talking only about short arrays here).
For median of 9 numbers, a little googling reveals the article Fast median search: an ANSI C implementation by N. Devillard, which points to the article Implementing median filters in XC4000E FPGAs by J. L. Smith, which provides this self-explanatory “sorting network” to get the median using 19 comparisons:
In terms of C:
Edit: this file also contains the code for getting the median of 3, 5, 6, 7, 9 and 25 numbers.