implementing demerge/merge algorithm