refactored merge and sort method