KANO, Nigeria — With anger swelling over corruption, inequality and a devastating Islamist insurgency in the nation’s north, Nigerians by a wide margin chose an austere former general who once ruled with an iron hand to be their next president, according to election results on Tuesday.

The election was the most competitive presidential race ever in Nigeria, one of the largest democracies in the world. Now, if power is handed over peacefully, it will be a major shift for the nation — the first transfer between civilians of different parties in a country that has spent much of its post-colonial history shaken by military coups.

With results from all of Nigeria’s 36 states counted, the former military ruler, Muhammadu Buhari, delivered a crushing defeat to President Goodluck Jonathan, getting nearly 55 percent of the vote to Mr. Jonathan’s 45 percent.