[英]Java sorting program, getting a confusing output
public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
greatest = array[0];
for (zz = 0; zz < 5; zz++) {
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray);
}
}
输出:
sorted array: [I@1a16869
sorted array: [I@1a16869
sorted array: [I@1a16869
sorted array: [I@1a16869
sorted array: [I@1a16869
这只是一个基本的小程序,我正在尝试弄清逻辑。 我无法改进它或使其成为类或方法,因为我什至没有正确地获得输出。
如果您尝试使用自己的算法,建议您尝试使用IDE并调试代码。
如果要使用JDK提供的算法,可以使用:
Arrays.sort(array);
关于输出,您正在尝试打印数组,而数组是java中没有toString实现的对象。 因此,您应该将打印语句更改为:
System.out.println("sorted array: "+Arrays.toString(copyarray));//without surrounding for loop to get what its after each step of sorting elements.
或者,如果您想保留for循环,则可以使用基于索引的数组访问方式:
System.out.print(copyarray[i] + " ");
您正在打印参考而非值用途:
for(int i = 0; i < copyarray.length; i++ ) {
System.out.println("Value : " + copyarray[i]);
}
我也建议使用Arrays.sort(array);
写吧
private int[] values = { 9,2,5,3,1,7,0 };
public void printSorted() {
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
System.out.println("Value: " + values[i]);
}
}
实际上,这里没有答案是正确的。
问题的核心是您没有在每次迭代中重新初始化greatest
的变量。 设置为array[0];
在开始时,它再也不会改变。 这应该进入循环。
public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
// greatest = array[0]; <---- Don't do it here
for (zz = 0; zz < 5; zz++) {
greatest = array[0]; // <--- Initialize greatest here and not before the loop
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray[i]);
}
}
附带说明,您不正确地打印了数组,应该使用copyarray[i]
而不是copyarray
。
这两个更改,下面是输出:
sorted array: 55
sorted array: 6
sorted array: 4
sorted array: 3
sorted array: 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.