Magic!
... not really. The system uses a Bayesian-like method to check the content and title of your question, looks at previously asked questions with similar word choices, then suggest the tags that deems appropriated (or so it should be). HereHere you can see the original post describing how it works.
That's why retagging is important, because it teach the system which questions should use which tag.