gpt4 book ai didi

java - 插入排序技术代码错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:56 26 4
gpt4 key购买 nike

最近一直在学习插入排序,想出了这段代码:

public int[] Sort(int a[]){
for(int i=1;i<a.length;i++){
int term=a[i];
int j=i-1;

//Sorting
while(j>=0 && term<a[j]){
a[j+1]=a[j];
j--;
}

a[j]=term;
}

return a;
}

但是当我执行这段代码时,它显示ArrayIndexOutofBoundsException。无论我错在哪里,请指导我。

最佳答案

根据错误状态,显示错误在

a[j] = term

因此,如果您仔细观察,您会发现 while 循环会导致 ArrayIndexOutofBoundsException。所以你可以这样写代码:

public static int[] Sort(int a[]){
for(int i=1;i<a.length;i++){
int term=a[i];
int j=i-1;

//Sorting
while(j>=0 && term<a[j]){
a[j+1]=a[j];
j--;
}

a[j+1]=term;
}

return a;
}

关于java - 插入排序技术代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21793822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com