Italian Bagnaia, who had started on pole position for a fifth consecutive race, finished ahead of 2020 world champion Joan Mir of Suzuki and Australian Jack Miller, also on a Ducati.
Starting from a lowly seventh on the grid, Frenchman Quartararo fell five laps from the end of the race on the same circuit where he had won the Portuguese MotoGP in April. It was the first time this season he had failed to finish.
While there was plenty of drama behind him, Bagnaia, who started from pole, was never challenged as he claimed his third win of the season, handing Ducati the constructors title. "I think it's my best weekend in MotoGP," Bagnaia said.
"I enjoyed every single session this weekend. When you feel so great with your bike everything comes more easily." The race ended prematurely under red flags, after Iker Lecuona and local rider Miguel Oliveira, both on KTM bikes, crashed two laps from home. Both riders were conscious, although Oliveira required a check-up at the circuit medical centre.
With just one race left this season in Valencia next weekend, Bagnaia and Mir are guaranteed to finish second and third in the championship. Second place was Mir's best finish of the season but he could never challenge Bagnaia, who is known as 'Pecco'. "Today Pecco was just better," he said. "He was not making one mistake. I was waiting for all race and it wasn't coming."
"Pecco had amazing pace," said the Australian. "He was like a hammer chipping away at us. I made a small mistake. Joan and I were doing that throughout the race, whereas he stayed like a rock out the front." In front of a crowd of around 28,000 spectators, seven-time MotoGP world champion Valentino Rossi finished 13th in the penultimate race of his career.
The 42-year-old will ride off into retirement next week. Spanish rider Pedro Acosta won the Moto3 world title at the age of 17 on Sunday, marking himself out as a name to watch after triumphing in the Algarve race. Acosta won six of 17 races in a spectacular debut season at this level and took the flag in Portugal after the fall of Italian rider Dennis Foggia, the only rival who had a chance of beating him to the title.
At 17 days and 166 days, KTM rider Acosta becomes the second-youngest world champion in any Moto category behind only Loris Capirossi of Italy, who keeps his record by a single day. Australian Remy Gardner won the Moto2 race and heads into the final race with a 23-point lead over his closest rival Spaniard Raul Fernandez who was a distant second.