finished bg algorithm in ex4