Reputation: 27
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..
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
Upvotes: 0
Views: 134
Reputation: 585
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]);
}
}
Upvotes: 0
Reputation: 178263
For some reason, you are comparing the element past the current index of j
; you're always using j+1
. Stop adding 1 to j
wherever you use it. You're skipping the first element that way.
if(a[i] > a[j])
{
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
Upvotes: 1