π/4 · √N steps. For a classical algorithm, the expected number of queries is N/2.
The algorithm works by repeatedly applying two operations:
- Oracle — flips the phase of the target state, marking it with a negative amplitude
- Diffuser — reflects all amplitudes about their average, amplifying the marked state
r = ⌊π/4 · √N⌋ iterations, measuring the register yields the target with high probability.
Searching a 4-qubit register
This example uses 4 qubits (N = 16 states) and searches for the state|110⟩ in the first three qubits, treating the fourth qubit as an ancilla that is summed over.
Initialize the register in superposition
Create four qubits in Each of the 16 states starts with amplitude
|0⟩ and apply Hadamard to each. This creates a uniform superposition over all 16 basis states.1/√16 = 0.25 and probability 1/16 ≈ 0.0625.Calculate the number of iterations
The optimal number of Grover iterations for N items is With 4 qubits, N = 16 and
r = ⌊π/4 · √N⌋.r = ⌊π · √16 / 4⌋ = ⌊π⌋ = 3.Apply the oracle
The oracle marks the target pattern The X gates on
|110⟩|x⟩ — all states where the first three qubits are 110, regardless of q3. It does this by temporarily flipping q2 and q3, applying a 3-controlled-NOT through q3 (with q3 sandwiched by Hadamards to convert it to a phase flip), then restoring q2 and q3.q2 and q3 convert the target pattern |110⟩ into |111⟩ so that the 3-controlled-NOT (CCCNOT) fires. The H–CCCNOT–H sequence on q3 implements a phase flip (−1) on the |111⟩ state. The final X gates restore the computational basis.Apply the diffuser
The diffuser reflects all amplitudes about their mean, amplifying the negative-amplitude (marked) state.This is the standard Grover diffuser: H transforms to the Hadamard basis, X flips all bits so
|0000⟩ becomes the target of the multi-controlled phase flip, and the final H and X restore the original basis.Iterate and measure
Wrap the oracle and diffuser in a loop for Output:The state
r iterations, then print the state grouped by the first three qubits and q3 separately.[110 0] (first three qubits 110, ancilla 0) has probability 0.9613 — over 96%. All other states have probability 0.0026. Measuring the first three qubits will yield 110 with 96% confidence.