implementing insert algorithm