impement beiderMorse algorithm