Magnets align themselves according to the strongest magnet around them.
When a magnet is suspended freely, it is only influenced by the Earth's magnetic field. However, when a strong magnet is brought near it, this magnet is influenced by the magnetic field of the strong magnet.
So we can say, magnets align themselves according to the strongest magnet around them.