【发布时间】:2017-02-18 23:34:31
【问题描述】:
我教授的一项任务对我来说特别棘手。我必须编写一个带有以下标头的方法:
public static void sort(String[] a)
该方法应按递增顺序对数组 a 进行排序(不确定这是否意味着“字符串长度的递增顺序”,但这是我的假设)。
问题:我不允许以任何方式更改方法头,不允许使用合并排序或快速排序,也不允许使用任何无关的包/库。
不允许合并排序和快速排序对我来说没什么大不了的,因为我也不太喜欢,但我发现如果不传递一些辅助参数(存储一个数组的索引位置)将在递归调用中使用。
这是我在经历了几个小时的挫折之后想出的:
public static void sort(String[] a)
{
String temp;
// Note that we use a.length - 1 in the loop condition
// to account for the fact that we will be checking the value of the
// element at the current index against the value of the element at the NEXT index.
// Since array indices are zero-based, iterating from 0 to a.length would result
// in an ArrayIndexOutOfBoundsException when we index = 7, since the
// base case would check a[7] against a[8], the latter of which does not exist
for (int index = 0; index < a.length - 1; index++)
{
if (a[index].length() < a[index + 1].length())
{
continue;
}
else
{
temp = a[index + 1];
a[index + 1] = a[index];
a[index] = temp;
// Recursive call to the sort method
sort(a);
}
}
}
基本思想是使用 for 循环“多次”检查每个元素,以鼓励每个元素进入其“适当位置”(在“递增顺序”意义上)。我怀疑它是否正确,虽然我还没有测试过(教授还没有为这个作业上传驱动程序)。
如果没有,有人能指出我正确的方向吗? Array 或 String 类中似乎没有任何方法在这里有用。我什至没有在这里看到递归的用途。如果我只是一遍又一遍地将相同的数组传递给方法,那不是没用吗?
【问题讨论】:
-
只实现冒泡排序?
-
如果分配是使用递归,那么也许你可以将原始数组分解成更小的数组并将它们传递给递归方法,这样你就不需要额外的参数了。如果作业不是关于递归,请听从 Andy 的建议:实现经典冒泡排序
-
一定要递归吗?
-
旁注:通常,对
Strings 进行排序按字典顺序而不是按长度;你应该和教授澄清一下