RIO DE JANEIRO — A far-right candidate who has spoken fondly of Brazil’s onetime military dictatorship came close to an outright victory in the country’s presidential election on Sunday, as Brazilians expressed disgust with politics as usual and endorsed an iron-fisted approach to fighting crime and corruption.
Voters delivered a first-round victory to Jair Bolsonaro, who had stunned the political establishment by rising to the top of a crowded presidential field despite a long history of offensive remarks about women, blacks and gays.
With 99.9 percent of votes tallied, Mr. Bolsonaro had 46 percent of the vote; he needed 50 percent to avoid a runoff. His nearest rival finished far behind, with 29 percent.
With the presidency in sight, Mr. Bolsonaro said Sunday night he intended to unite a nation that is “on the brink of chaos” and said, “Together we will rebuild our Brazil.”
Brazilians will now vote in the runoff election on Oct. 28 between Mr. Bolsonaro and Fernando Haddad, the leftist Workers’ Party candidate. The two men represent radically different visions for Brazil, the world’s fourth-largest democracy, where leftists have won the presidency in every election since 2002.
However strongly Mr. Bolsonaro performed on Sunday, he remains an extremely divisive figure who alienated large segments of Brazil’s highly diverse population during the campaign.
But political analysts said Sunday night that Mr. Haddad faces a daunting task in the second round to rally a majority of Brazilians to his side.
Laura Carvalho, an economist at University of São Paulo, said the best bet for the Workers’ Party’s candidate would be to focus on pocketbook issues over the next three weeks. “Instead of focusing on racism and misogyny, which did not have much effect, they should focus on the economic agenda and the anti-worker aspect of the Bolsonaro candidacy,” Ms. Carvalho said.
While several of Brazil’s neighbors have steered to the right politically in recent years, a victory by Mr. Bolsonaro, a populist conservative who stands to join a growing roster of anti-establishment leaders around the world, would be a seismic conservative shift.
Critics of Mr. Bolsonaro and political analysts have watched his rise with alarm, fearing he could become an authoritarian leader in the mold of Recep Tayyip Erdogan of Turkey and Rodrigo Duterte of the Philippines.
Before running for president, Mr. Bolsonaro, a former Army captain with little to show for his seven terms in Congress, faced federal hate speech charges for homophobic, misogynist and racist comments. He also spoke with admiration and nostalgia for Brazil’s military dictatorship, during which 434 people were killed or disappeared and thousands were tortured from 1964 to 1985.
Rejected by mainstream parties, Mr. Bolsonaro struggled to find a running mate until early August, when he picked a recently retired general who has advocated military intervention as a means to purge a corrupt ruling elite. He has said he intends to appoint other military leaders to central roles.
Mr. Bolsonaro’s first-round victory was all the more remarkable because he lacked the backing of a major party and campaigned on a shoestring budget, relying mainly on social media to build a base. As of mid-September, the Bolsonaro campaign reported having spent about $235,000, a small fraction of the $6.3 million the Haddad campaign disclosed having spent.
Mr. Bolsonaro’s rise was enabled by the political divisions that have torn the country apart in recent years.
Brazilians were outraged as leaders of the traditional parties become ensnared in an ever-widening corruption investigation that began in 2014 and became ever more despondent as the economy sputtered, joblessness grew and crime soared.
While some voters remained loyal to the Workers’ Party — which governed from 2003 to 2016 — for its efforts to improve the lives of poor and working-class Brazilians, many came to hold it responsible for the graft and economic hardship of recent years.
Millions of Brazilians today enthusiastically embrace Mr. Bolsonaro’s radical approach to law and order — even it means killing criminals or political enemies, which were frequent themes for the candidate.
Georgewlany Smith, a 61-year-old public servant in Rio de Janeiro, said that an erosion of democratic norms and civil liberties is a price he is willing to pay for a more secure and prosperous Brazil.
“You have to consider what were the best times for Brazil,” Mr. Smith said shortly after he voted for Mr. Bolsonaro in the upscale Barra de Tijuca district. “Unfortunately it was the dictatorship.”
Mr. Bolsonaro has tapped into the simmering anger and desire for disruption of the status quo that has gripped many Brazilians. And he became the face of a growing conservative movement in a nation where evangelicals account for one in four voters and more than 90 federal lawmakers.
The candidate offered little in the way of a detailed policy road map — particularly regarding the country’s floundering economy. When pressed with questions, he offered up Paulo Guedes, a market-friendly economist he said he would appoint as finance minister to curtail the social spending that grew under the Workers’ Party.
The markets rallied as he took the lead in polls — but Mr. Bolsonaro is “not the pro-market liberal he pretends to be,” warned Monica de Bolle, a Brazilian economist who heads the Latin American Studies Program at Johns Hopkins University.
“He really stands out for having overly simplistic solutions to very complex problems, a characteristic that will certainly backfire,” she said.
Mr. Bolsonaro’s victory will most likely be denounced by many on the left as the undemocratic outcome of an election that excluded the towering politician in recent Brazilian history: former President Luiz Inácio Lula da Silva, a rousing former steelworker and union leader who rose to prominence in the 1970s and 1980s opposing the military dictatorship.
Mr. da Silva, who served two terms and left office in 2011 with a record-high approval rating, was the front-runner for much of the past year and appeared well positioned to return to the presidential palace. But he became ineligible to run for office after an appeals court early this year upheld a corruption and money laundering conviction against him.
After Mr. da Silva was remanded to prison in April to start serving a 12-year sentence, he continued to run a campaign from his cell. Roughly one month before the vote, his party settled on Mr. Haddad, a former education minister and mayor of São Paulo, to take his place on the ballot.
Mr. Haddad, 55, who comes across as an earnest intellectual and lacks Mr. da Silva’s fiery charisma, was unknown in much of the country and failed to galvanize core Workers’ Party voters who had identified with Mr. da Silva’s working-class roots and life story.
Some voters remain fiercely loyal to Mr. da Silva, though.
Anita Silva Lima, a 38-year-old waitress who lives in Rocinha, a low-income neighborhood in Rio de Janeiro, said on Sunday morning that she and her seven immediate relatives had voted for “Lula’s candidate,” resisting pressure from her boss, who urged her to back Mr. Bolsonaro.
“I don’t want a dictatorship — a lot of people died then,” said Ms. Lima, who is originally from the impoverished northeast, a Workers’ Party stronghold. “I don’t care about this corruption talk. Tell me the name of a politician who doesn’t steal? Bolsonaro steals, too.”
Others have lost faith in the Workers’ Party and feel the current race leaves them with no good options.
“They are all the same,” said Carlos Alberto da Silva, a 59-year-old driver in Rio de Janeiro who supported the Workers’ Party in 2014 and said he intended to signal his frustration by spoiling his ballot this year.
Among the striking surprises of Sunday’s election was the defeat of former President Dilma Rousseff of the Workers’ Party, who was running for the Senate. Public opinion polls had suggested she would easily win a seat in her home state of Minas Gerais, but Ms. Rousseff came in fourth.
Clara Araújo, a sociologist at the State University of Rio de Janeiro, said voters showed a strong disdain for the dominant political factions on Sunday.
“The dissatisfaction over the economic crisis, it seems to me, was channeled along with a discourse about conservative morals,” she said. Those who voted for Mr. Bolsonaro, she said, saw him as “the option for a certain order, a certain stability, even if this notion was based on easy ways out.”
Mr. Bolsonaro warned voters that returning the Workers’ Party to power would perpetuate a culture of graft that has been exposed in recent years and has tainted every large political party and several of the country’s top companies.
He also contended that under leftist rule, Brazil risked stumbling into an economic crisis like the one that has sparked a mass exodus in neighboring Venezuela.
Mr. Bolsonaro’s appeal grew steadily after he was stabbed last month while being carried aloft by supporters at a campaign rally in Minas Gerais state.
As most of his dozen rivals traveled around the country and participated in debates, Mr. Bolsonaro largely sat out the final month of the race recovering in a hospital in São Paulo and later at his home in Rio de Janeiro.
In recent days he has recorded daily videos broadcast live on Facebook weighing in on the news of the day. The unscripted, shaky clips were illustrative of a campaign that had an insurgent, improvisational feel from the start.
As a Bolsonaro victory appeared increasingly likely, ardent opponents protested online and in the streets under the motto: #EleNão, or Not Him, warning that the country’s democratic institutions could be eroded.
But influential evangelical and agribusiness lobbies rallied to his side in the final stretch, while investors and wealthy Brazilians backed him, believing that Mr. Bolsonaro would curtail social spending and implement market-friendly reforms.
Outside Mr. Bolsonaro’s beachfront apartment in Rio de Janeiro on Sunday night, supporters sang the national anthem and chanted “the captain has arrived” as the first results showed him winning by a large margin.
“Getting rid of the P.T. alone is not a solution, but it’s a first step toward fixing the country,” said Barbara Laureano, a 25-year-old business woman, referring to the Workers’ Party. “This is not about him as a person, it’s about an idea,” she said.
Lis Moriconi contributed reporting.