Fixed #14226 -- dependency calculation for complex M2M relations

See https://code.djangoproject.com/ticket/14226#comment:13 for details

I also refactored sort_depencies a tiny bit to make it more readable. I made a separate commit for this, since it shouldn't change behaviour and I'd rather keep that explicit. The commits can of course be squashed if that's preferred.

All tests pass under sqlite and postgres.