Refactor

* Define swap function to remove duplication