The Earth formed in a similar way to the other planets in our Solar System.
The entire System was originally a cloud of gas and dust particles. Eventually this cloud got big enough (and therefore massive enough) to become gravitationally unstable. The cloud started compacting - pulling towards the centre under the force of gravity.
The Laws of Physics state that angular momentum must be conserved. So as this cloud collapsed, it was pulled into a spinning disc.
As particles collided in this disc they stuck together, building clumps of material. The heaviest clumps moved towards the centre of the disc. Here they formed bigger and bigger clumps.
Eventually the clumps of material formed a quasi-stable system in the proto-planetary disc. These would then become the planets.
Just as the initial gas and dust cloud collapsed, condensing into a disc, the clump of matter that would eventually become the Earth was acted upon by gravity.
The Earth has sufficient self-gravity to change its shape. The force of gravity pulls towards the centre of the Earth (in every direction). A spherical shape is the best balance between gravitational pressure (in) and lithographic (strength of rocks) pressure (out).