The story of Ganga's sanctity involves several different characters and is quite complex. One day, Brahma collected the sweat of Vishnu's feet and created Ganga. Thus, being touched by two members of the Trimurthi, Ganga became very holy.
Several years later, a King named Sagar magically acquired sixty thousand sons. One day, King Sagar performed a ritual of worship for the good of the Kingdom. One of the integral parts of the ritual was a horse, which was stolen by the jealous Indra. Sagar sent all his sons all over the earth to search for the horse. They found it in the Underworld next to a penitent sage. Believing that the sage had stolen the horse, they hurled insults at him and caused his penance to be disturbed by assaulting. The sage opened his eyes for the first time in several years, and looked at the sons of Sagar. With this glance, all sixty thousand burnt to death.
The souls of the sons of Sagar wandered as ghosts since their final rites had not been performed. When Bhagiratha, one of the descendants of Sagar by a second wife learnt of this fate, he vowed to bring Ganga down to earth so that it could sweep away the ashes to heaven.
Bhagiratha prayed to Brahma that Ganga come down to earth. Brahma agreed, and he ordered Ganga to come down to the earth and then the underworld so that the souls of Bhagiratha's ancestors would be able to go to Heaven. The vain Ganga felt that this was insulting and decided to sweep the whole Earth away as she fell from the Heavens. Alarmed, Bhagiratha prayed to Shiva that he break Ganga's descent.
Ganga arrogantly fell on Shiva's head. But Shiva calmly trapped her in his hair and let her out in small streams. The touch of Shiva further sanctified Ganga. As Ganga traveled to the Underworld, she created a different stream to remain on Earth to help purify unfortunate souls there.