The Spanish authorities said on Saturday that they were installing a floating barrier near a sea wall between Morocco and the autonomous city of Ceuta, after a surge of tens of thousands of migrants into the territory two days ago raised questions about Spain’s ability to control its borders.

The announcement, from Spain’s Interior Ministry, came as a vast majority of those migrants — most of them young Moroccan men seeking work — appeared to have left the city, a Spanish exclave in North Africa. For those who have stayed, and who have tried to evade the police and angry crowds of locals, the next steps remained unclear.

At least 48,300 of the roughly 50,000 to 60,000 people who entered from Morocco had returned there by late Friday afternoon, according to Spain’s Interior Ministry, while hundreds more continued to leave throughout the night. A spokesperson for Spain’s government in Ceuta said at least 67 people died trying to enter the city in recent days.

In Ceuta on Friday, Prime Minister Pedro Sánchez of Spain announced that the country would install buoys to “create a containment barrier, a physical barrier, if only a visual one,” to strengthen the border.

The buoys will also comply with a recent ruling from Spain’s Supreme Court that prompted the influx of migrants this week, Mr. Sánchez said.

Mr. Sánchez blamed human traffickers for spreading misinterpretations about the ruling, which said that migrants intercepted at sea could not be immediately sent back unless they had bypassed a barrier while trying to reach Spanish territory.