BAGHDAD — Iraqis are still haunted by memories of black-clad death squads roaming Baghdad neighborhoods a decade ago, cleansing them of Sunnis as the country was convulsed by sectarian violence.

Many of the mass killings in the capital were done in the name of Moktada al-Sadr, a cleric best remembered by Americans for fiery sermons declaring it a holy duty among his Shiite faithful to attack United States forces.

The militia he led was armed with Iranian-supplied weapons, and Mr. Sadr cultivated a strong alliance with leaders in Tehran, who were eager to supplant the American presence in Iraq and play the dominant role in shaping the country’s future.

Now, the man once demonized by the United States as one of the greatest threats to peace and stability in Iraq has come out as the surprise winner of this month’s tight elections, after a startling reinvention into a populist, anticorruption campaigner whose “Iraq First” message appealed to voters across sectarian divides.