Java 中的递归冒泡排序
我正在尝试用 Java 编写递归冒泡排序,但出现索引越界异常。我做错了什么以及为什么会收到此错误? 这是我的代码:
public static <T extends Comparable< ? super T>>
void sort(T [] a){
T tmp;
for(int i=0;i<a.length;i++){
if(a[i].compareTo(a[i+1])>0){
tmp = a[i];
a[i]=a[i+1];
a[i+1]=tmp;
sort(a);
}
System.out.println("i:"+i+" "+a[i]);
}
另外,即使它对数组进行排序并且我在最后收到错误,它正在打印所有步骤,如何让它打印最后一个最终排序的数组? 这可能是一个简单的答案,但我的大脑现在很混乱,无法正常思考。 提前致谢。
I am trying to write a Recursive Bubble sort in Java and I'm getting an Index Out of Bounds Exception. What am I doing wrong and why am I getting this error?
Here is my code:
public static <T extends Comparable< ? super T>>
void sort(T [] a){
T tmp;
for(int i=0;i<a.length;i++){
if(a[i].compareTo(a[i+1])>0){
tmp = a[i];
a[i]=a[i+1];
a[i+1]=tmp;
sort(a);
}
System.out.println("i:"+i+" "+a[i]);
}
Also, even tho it sorts the array and I get the error at the end, it is printing all of the steps, how do I make it print the last final sorted array?
Is probably a simple answer but my brain is fried right now and can't think straight.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当 i
i
i
i
i
i
i
i
i
i
i
a.length-1
,因为在您的代码中您访问位置i+1
,并且当i == a.length - 1
时i+1 将尝试访问数组末尾不存在的元素 - 因此,超出范围。
The loop should stop when
i < a.length-1
, because in your code you access the positioni+1
, and wheni == a.length - 1
theni+1
will be trying to access an element off the end of the array that doesn't exist - hence, out of bounds.您已经编写了循环,以便
i
得到与a.length - 1
一样的位。然后,您尝试访问a[i+1]
,当i == a.length - 1
时,这是一个越界索引。将循环限制降低 1。You've written your loop so that
i
gets as bit asa.length - 1
. Then you are trying to accessa[i+1]
, which is an out-of-bounds index wheni == a.length - 1
. Lower your loop's limit by 1.上限应该是length-1
The upper limit should be length-1
发生
IndexOutOfBoundsException
是因为当i
位于最后一个索引(a.length 时,循环尝试访问
,超出范围。a[i+1]
- 1)要修复此问题,请调整循环运行直到
i
i
i
i
i
i
i
i
i
i
i
i
i a.length - 1
,因此a[i+1]
始终有效:发生错误是因为循环试图访问不存在的索引
(a[ i+1]
当i
位于a.length - 1)
时。该修复确保有效的索引访问并让数组正确排序,最后仅打印一次最终排序的数组。The
IndexOutOfBoundsException
happens because your loop tries to accessa[i+1]
wheni
is at the last index(a.length - 1)
, which goes out of bounds.To fix it, adjust the loop to run until
i < a.length - 1
, soa[i+1]
is always valid:The error happened because the loop tried to access an index that doesn’t exist
(a[i+1]
wheni
is ata.length - 1)
. The fix ensures valid index access and lets the array sort correctly, printing the final sorted array only once at the end.试试这个。
Try this.