Basically, the reason that things corrode is that there are dissimilar metals, one with more electrons than the other creating a voltage between them. So your part is a battery and the ocean is the "wire". The electrons move from your part (corroding them), to other parts with less electrons. If instead you have a sacrificial piece of zinc, the zinc has more electrons than your part so the electrons will come from the sacrificial piece of zinc instead of your part. Think of it like a lightning rod, but for corrosion instead of lightning. It's more complicated than this, but that's the general idea.
"They are made from a metal alloy with a more "active" voltage (more negative reduction potential / more positive electrochemical potential) than the metal of the structure. The difference in potential between the two metals means that the galvanic anode corrodes, so that the anode material is consumed in preference to the structure."
https://en.wikipedia.org/wiki/Galvanic_anode
I worked on a 120m old passenger ship for a while. During dry-dock each year we'd put 8 or so 2kg (ish) zinc anodes around the hull, a welded bracket around each one.
The trouble was that they're pretty expensive, and zinc has a great resale value - so we had to do extra watches around the lower decks with rigged firehoses to try and stop local divers stealing them who knew we'd just come out of drydock. (This was in the Philippines). We lost several that way.