reorder main algorithm