【发布时间】:2017-01-25 21:51:38
【问题描述】:
下面的程序是在 java 中,它假设按升序对数组元素进行排序,但它不是这样运行的。请尝试下面的程序并解释为什么它没有将某些值存储在“第二个”数组中。第二个数组中的一些值存储为 0。我无法计算。请解决这个程序并让我知道。谢谢。
public static void main(String[] args) {
int first[]={9,8,2,6,3};
int second[]=new int[5];
for(int i=0;i<first.length;i++){
int count=0;
for(int j=0;j<second.length;j++){
if(first[i]<first[j]){
count++;
}
}
if(count == 0){
second[4]=first[i];
}
if(count == 1){
second[3]=first[i];
}
if(count == 2){
second[2]=first[i];
}
if(count == 3){
second[1]=first[i];
}
if(count == 4){
second[0]=first[i];
}
System.out.print(second[i]);
}
}
【问题讨论】:
-
如果你只想对一个 int 数组进行排序。有什么原因,为什么你不使用 Arrays.sort()?
-
你知道如何调试 Naveen 吗??
-
如果您想在不使用 Arrays.sort() 的情况下对数组进行排序,为什么不查找诸如合并排序、快速排序甚至冒泡排序之类的排序算法?
-
我可能不太了解,但这是否是一个有效的排序算法?
-
您的问题是,您覆盖了
second中的值。因为count可以多次使用相同的值。这可以通过调试轻松找到。 stackoverflow.com/questions/18977397/…