Merge sort and sort_by_key optimization and bug fixes