Added two sorting steps to avoid error in merge.