gpt4 book ai didi

java - 如何将我的插入排序代码修复为升序?我的输出顺序错误

转载 作者:行者123 更新时间:2023-12-01 19:46:31 25 4
gpt4 key购买 nike

public class InsertionSort{

public static void main(String [] args){

int [] a = {45,23,4,6,2};

for(int i = 0; i< a.length; i++){
for(int j = i; j>0; j--){

if(a[j]< a[j-1]){

int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;

System.out.println(a[j]);
}

}
}
}
}

输出:

4545234523452364

我希望它按升序排列。

最佳答案

您的数组已经排序,您只需将 print 语句移出循环即可

public static void main(String [] args){
int [] a = {45,23,4,6,2};
for(int i = 0; i< a.length; i++){
for(int j = i; j>0; j--){
if(a[j]< a[j-1]){
int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
// Arrays.stream(a).forEach(System.out::println); -- Java 8
for (int idx = 0; idx < a.length; idx++) {
System.out.println(a[idx]);
}
}

关于java - 如何将我的插入排序代码修复为升序?我的输出顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53057082/

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