Swapping two qubits

This circuit swaps two qubits:

That means if we started out in the |"01"> state, we would end up in the |"10"> state and vice versa. Inputs of |"00"> or |"11"> would be unchanged as swapping would have no effect. How does this gate work? Note that for the first and third CNOTs, the control qubit is the first qubit and the target qubit is the second, while for the second CNOT, the control qubit is the second and the target qubit is the first. Let's trace it out step by step:

Input

After first CNOT After second CNOT After third CNOT (output)

|"00">

|"00"> |"00"> |"00">

|"01">

|"01"> |"11"> |"10">

|"10">

|"11"> |"01"> |"01">

|"11">

|"10"> |"10"> |"11">

It's straightforward to see the swap when the two input qubits are in a state that is either 100% |"1"> or 100% |"0"> as we have seen here, but it is important to note that the swap will work just as well with qubits where one or both are instead a mix (superposition) between |"1"> and |"0">. For example, if initially the first qubit is 90% |"1"> and 10% |"0">, and the second qubit is 50% |"1"> and 50% |"0">, then after the swap circuit is executed, the first qubit will be 50% |"1"> and 50% |"0"> , and the second qubit will be 90% |"1"> and 10% |"0">.