Java插入排序不排序



我通过插入编写了一个java排序算法,代码编译但不排序:(.如果有人能指出任何缺陷,我非常感谢,java没有…

public class Sort {
public static int[] sort(int[] x) {
int[] y = new int[x.length];
for(int i = 0; i < x.length; ++i) {
int j = 0;
while (y[j] < x[i] && j < i) ++j;
for (int k = i-1; k >= j; --k) y[k+1] = y[k];
y[j]=x[i];
}   
return y;
}
public static void main(String[] args) {
int[] size = new int[10];
for(int k=0; k<size.length; ++k ) {
size[k]=(int)(Math.random()*20);
System.out.println(size[k]);
}
System.out.println(sort(size));
}}

[I@39ed3c8d通过调用int数组上的toString()返回,然后使用System.out.println打印。

您可能想要System.out.println(Arrays.toString(sort(size)));

您正在打印尺寸参考,即[I@39ed3c8d

这应该有助于您理解:

public class Sort {
public static int[] sort(int[] x) {
int[] y = new int[x.length];
for(int i = 0; i < x.length; ++i) {
int j = 0;
while (y[j] < x[i] && j < i) ++j;
for (int k = i-1; k >= j; --k) y[k+1] = y[k];
y[j]=x[i];
}   
return y;
}
public static void main(String[] args) {
int[] size = new int[10];
System.out.println("Befor sorting");
for(int k=0; k<size.length; ++k ) {
size[k]=(int)(Math.random()*20);
System.out.print(size[k]);
System.out.print(" ");
}
size = sort(size);
System.out.println("nAfter sorting");
for(int i = 0; i<size.length; i++){
System.out.print(size[i]);
System.out.print(" ");
}
}}

该随机性是以下结果:System.out.println(sort(size));

改为:

size = sort(size);
for(int k=0; k<size.length; ++k ) {


System.out.print(size[k] + " " );
}

最新更新