【发布时间】:2017-08-30 14:52:13
【问题描述】:
我的目标是将 ar[] 数组中的元素移动到 sorted[] 数组中,并将它们从最小到最大排序。我在这部分遇到了麻烦,因为我的循环应该找到数组中的最小元素,然后用大数字替换元素。我想我的大部分代码都写好了,但是当我运行程序时,sorted[] 数组中的每个元素都是 2。我在这里做错了什么?
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
ar[i] = 1000000;
}
// print sorted array:
for (int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
【问题讨论】:
-
在排序前复制数组。
-
注意内部循环没有引用
i?为什么它的结果会因索引而变化? -
这是一个错误的代码
ar[i] = 1000000;此外,为什么要将排序后的元素放在另一个数组中?如果您想保留原件,只需复制原件并处理您当前的阵列。