【发布时间】:2021-03-08 19:49:32
【问题描述】:
我需要做一个练习,给定一个列表,我只需要使用递归方法(不使用 while、do while、for、foreach)对内容进行排序。
所以...我正在苦苦挣扎(现在已经超过 2 小时),我什至不知道如何开始。 函数必须是
List<int> SortHighestToLowest (List<int> list) {
}
我想我应该检查前一个数字是否大于实际数字等等,但是如果最后一个数字大于列表中的第一个数字怎么办?这就是为什么我很头疼。
感谢您的帮助,非常感谢。
[编辑]
我完成了练习,但老师说我不应该像这里那样使用外部变量:
List<int> _tempList2 = new List<int>();
int _actualListIndex = 0;
int _actualMaxNumber = 0;
int _actualMaxNumberIndex = 0;
List<int> SortHighestToLowest(List<int> list)
{
if (list.Count == 0)
return _tempList2;
if (_actualListIndex == 0)
_actualMaxNumber = list[0];
if (_actualListIndex < list.Count -1)
{
_actualListIndex++;
if (list[_actualListIndex] > _actualMaxNumber)
{
_actualMaxNumberIndex = _actualListIndex;
_actualMaxNumber = list[_actualListIndex];
}
return SortHighestToLowest(list);
}
_tempList2.Add(_actualMaxNumber);
list.RemoveAt(_actualMaxNumberIndex);
_actualListIndex = 0;
_actualMaxNumberIndex = 0;
return SortHighestToLowest(list);
}
练习已经完成并且我批准了(也感谢其他练习)但我想知道是否有一种方法可以不使用 外部变量 并且不使用 System.Linq 喜欢String.Empty 的回复(我只是好奇,社区帮助我解决了我的问题,我很感激)。
【问题讨论】:
-
这能回答你的问题吗? Bubble sort using recursion in C#
-
@devNull 不,但它是一个开始,我将使用它作为“模板”。谢谢!
-
您可能想为
List<T> where T:IComparable这样做。这将是相同的逻辑(除了您将使用IComparable方法而不是<或>之类的方法)。由于整数是可比较的,它们将正常工作 -
因感知到“焦点”而请求关闭的人或许应该注意Is it always a good idea to demand the OP “post some code”?