When turbulence in the air sends particles crashing into each other, some electrons get ripped loose. The loose electrons end up with either a positive or negative charge. In a thunderstorm, these particles are usually tiny slivers of ice, water droplets, or pieces of hail.
In a thunderstorm, the heavier particles of hail end up with a negative charge. These fall to a lower altitude within the clouds. Lighter particles (like ice slivers and frozen water droplets) usually end up with a positive charge and are carried by the winds to higher altitudes. This creates something like the top and bottom of a battery.
The air breaks down and becomes a conductor. Like a piece of wire, the air lets the opposite charges attract, creating a spark. Because the air is churning wildly, it's almost impossible to expect all the particles of the correct charge to be perfectly lined up, so when the spark hits an adjacent chunk of air that is not the correct charge, it zigs and zags.