[英]Sorting an array doesn't take the first element to compare(java programming)?
I'm trying to sort an array that include 5 numbers(size=4) from largest to smallest, but I spend a long time and I don't know why my code don't take the first element to be sorted.. 我正在尝试对包含5个数字(大小= 4)(从大到小)的数组进行排序,但是我花了很长时间,而且我不知道为什么我的代码没有采用第一个要排序的元素。
This is My code: 这是我的代码:
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]);
}
}
}
and this is the output: 这是输出:
5 14 10 -1 -2 5 14 10 -1 -2
For some reason, you are comparing the element past the current index of j
; 由于某种原因,您正在比较当前索引
j
的元素; you're always using j+1
. 您一直在使用
j+1
。 Stop adding 1 to j
wherever you use it. 无论在何处使用,都不要在
j
加1。 You're skipping the first element that way. 您正在以这种方式跳过第一个元素。
if(a[i] > a[j])
{
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
It's a bubble sort. 这是一种泡沫。 You can find some explanation here and here .
您可以在这里和这里找到一些解释。
public static void main(String args[]){
int[] vet = {8, 9, 3, 5, 1};
int aux = 0;
int i = 0;
System.out.println("Original Array: ");
for(i = 0; i<5; i++){
System.out.println(" "+vet[i]);
}
System.out.println(" ");
for(i = 0; i<5; i++){
for(int j = 0; j<4; j++){
if(vet[j] > vet[j + 1]){
aux = vet[j];
vet[j] = vet[j+1];
vet[j+1] = aux;
}
}
}
System.out.println("Ordered Array:");
for(i = 0; i<5; i++){
System.out.println(" "+vet[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.