first merge algorithm