changed stay in mid algorithm