Refactored median algorithm