我正在尝试对包含 5 个数字(size=4)的数组进行从大到小的排序,但是我花了很长时间,而且我不知道为什么我的代码不对第一个元素进行排序..
这是我的代码:
public class sortingS
{
public static void main(String []args)
{
int a[]={5,-2,10,14,-1};
for(int i=0; i<a.length; i++)
{
for(int j=0; j<i; j++)
{
if(a[i]>a[j+1])
{
int temp=a[j+1];
a[j+1]=a[i];
a[i]=temp;
}
}
}
for(int i=0; i<a.length; i++){
System.out.println(a[i]);
}
}
}
这是输出:
5 14 10 -1 -2
最佳答案
由于某种原因,您正在比较 j
当前索引之后的元素;你总是使用j+1
。无论您在哪里使用 j
,都不要再将 1 添加到它。您将这样跳过第一个元素。
if(a[i] > a[j])
{
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
关于java - 对数组进行排序不需要比较第一个元素(java编程)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952999/