java 递归插入排序
我有一个数组,必须使用插入排序对它们进行排序。我尝试使用 CompareTo 方法来遍历数组并查看更大的值。我遇到了一个问题,因为我试图用一个显然不起作用的字符串引用数组索引(即在compareTo(a[key]))。
任何有关如何执行此操作的建议或提示将不胜感激。
这就是我到目前为止所拥有的。这是一个好的开始吗?还是朝着正确的方向开始?
public void insertionSort()
{
insertionSort(a.length-1);
}
private void insertionSort(int n)
{
String temp;
if(n <= 1)
{
//Do nothing, easiest case
}
else
{
for(int i = 1; i < a.length; i++)
{
int j;
String key = a[i];
while((j >= 0) && (a[i].compareTo(a[key]) > 0))
{
a[i+1] = a[i];
j--;
}
a[i+1] = key;
}
insertionSort(n-1);
}
}
i have an array and have to sort them using insertion sort. i tried to use the compareTo method to run through the array and see whats bigger. I ran into a problem because i was trying to reference an array index with a string which obviously didntwork (thats at compareTo(a[key])).
any suggestions or hints as to how to do this would be appreciated.
this is what i have so far. is it a good start? or a start in the right direction?
public void insertionSort()
{
insertionSort(a.length-1);
}
private void insertionSort(int n)
{
String temp;
if(n <= 1)
{
//Do nothing, easiest case
}
else
{
for(int i = 1; i < a.length; i++)
{
int j;
String key = a[i];
while((j >= 0) && (a[i].compareTo(a[key]) > 0))
{
a[i+1] = a[i];
j--;
}
a[i+1] = key;
}
insertionSort(n-1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的第一个建议是,如果传递所需的参数,通常会更容易理解方法。完全不清楚
a
是什么;我希望公共insertionSort
方法将要排序的对象作为参数。 (我想如果你在自己的类似列表的类上定义它,它并没有那么糟糕,但听起来不像是这样的用法)。同样,我也不完全确定
n
应该是什么(大概是您知道已排序的索引),但您根本不在私有方法的主体中使用它,所以您只是做同样的事情n
次。您似乎还交换了
a
的元素,而在插入排序中不需要这样做。这看起来更像是冒泡排序。首先尝试将方法编写为伪代码(例如注释)以布局您的方法,然后用一小段代码充实每个注释。这样做可以避免过于陷入细节,通常概念性错误会显得更加明显,也更容易避免。这可能看起来像:
My first suggestion would be that it's usually easier to understand a method if you pass in the required arguments. It's not clear at all what
a
is; I'd expect the publicinsertionSort
method to take as an argument the objects to sort. (I suppose if you're defining this on your own list-like class it's not as bad, but it doesn't sound like that's the usage).Likewise I'm not entirely sure what
n
is supposed to be (presumably the index beyond which you know is sorted) but you don't use it at all in the body of the private method, so you're just doing the same thingn
times.You also appear to be swapping elements of
a
, which you shouldn't need to do in an insertion sort. This looks more like a bubble sort.Try writing the method as pseudocode (e.g. comments) first to lay out your approach, then flesh out each comment with a small bit of code. Doing this can avoid getting too bogged down in the detail, and usually conceptual mistakes will appear more obvious, and be easier to avoid. This might look something like:
替换内循环如下:
Replace the inner loop as follows:
只需将其更改为
a[j].compareTo(key)
(请注意,您要比较a[j]
,而不是a[i]
)。您还需要初始化j
,正如 smas 所评论的那样。Just change it to
a[j].compareTo(key)
(note that you want to comparea[j]
, nota[i]
). You also need to initializej
, as smas commented.