The hugely popular Dane produced a display of real quality to win 6-4 2-6 6-2 and make the last eight at a grand slam for the first time since the Australian Open in 2012.
The last time the Dane beat the Russian was at Flushing Meadows at the same stage four years ago.
Wozniacki has been in fine form and was the better player in the opening set, but it was no surprise to see Sharapova hit back in the second.
Because of the hot and sticky conditions, the heat rule was in effect, meaning a 10-minute break between the second and third sets.
Sharapova took too long, though, and was given a time violation, while Wozniacki then complained to the umpire about the time her opponent was taking between serves.
Wozniacki came out for the decider with a real sense of determination and made the breakthrough in spectacular fashion in the fourth game.
Somehow the 10th seed chased down a succession of lost causes before Sharapova netted a volley, prompting Wozniacki to whip up the adoring crowd.
And there was no wavering from the 24-year-old, who seized her first opportunity to clinch the match with a backhand winner that cleaned the line.
Wozniacki said: “It means so much to me. Things have been a bit up and down this year. To win against a champion like Maria is an unbelievable feeling.”
In the quarter-finals, Wozniacki will play 13th seed Sara Errani, who ended the emotional run of qualifier Mirjana Lucic-Baroni.
The Croatian was back in the fourth round at a slam for the first time since reaching the Wimbledon semi-finals aged 17 in 1999.
Family and financial problems derailed her career but her love for tennis never wavered and she is finally back on the big stage. The statistics told the story of a match between two very different players, with Lucic-Baroni hitting 46 winners compared to just four for Errani. Meanwhile fourth seed David Ferrer became the first top-10 man to go out after losing to France’s Gilles Simon.
Ferrer went down 6-3 3-6 6-1 6-3.