implemented team flipping algorithm