rewrote the merging algorithm using functional style programming