Sharapova, who lost to Serena Williams in last year's final, crumbled in the opening set when she held her serve just once.
But Halep's serve dipped in the second set, and Sharapova started hitting pinpoint ground strokes that kept the Romanian running. The ninth-ranked Russian converted both her break points in the set to even the match.
Sharapova then pulled away in the deciding set with an early break to follow up her triumph in Stuttgart with a maiden title in Madrid.
Since the 2011 French Open, Sharapova has a 47-3 record on clay — with all three defeats coming to Williams. The top-ranked American was the two-time defending champion in Madrid but withdrew with a leg injury on Friday.
"I don't know how I pulled it off," Sharapova said after winning her 32nd career title. "I came close last year, and I didn't have a great first set today, but I knew it wasn't over until the last point was played."
Sharapova looked dejected midway through the first set as she hit four double-faults, but she seemed to regain her focus at the start of the second.
As Sharapova celebrated the win, Halep slumped in her chair dejectedly despite having reached her first Masters final.
Later, top-ranked Rafael Nadal looks to become the first player to defend his title when the three-time champion faces Japan's Kei Nishikori in the men's final.